Find if nested key exists in json python
Asked Answered
D

5

7

In the following JSON response, what's the proper way to check if the nested key "C" exists in python 2.7?

{
  "A": {
    "B": {
      "C": {"D": "yes"}
         }
       }
}

one line JSON { "A": { "B": { "C": {"D": "yes"} } } }

Desireedesiri answered 4/3, 2013 at 0:17 Comment(0)
E
2

Use the json module to parse the input. Then within a try statement try to retrieve key "A" from the parsed input then key "B" from the result and then key "C" from that result. If an error gets thrown the nested "C" does not exists

Empurple answered 22/3, 2013 at 23:17 Comment(0)
D
10

This is an old question with accepted answer, but I would do this using nested if statements instead.

import json
json = json.loads('{ "A": { "B": { "C": {"D": "yes"} } } }')

if 'A' in json:
    if 'B' in json['A']:
        if 'C' in json['A']['B']:
            print(json['A']['B']['C']) #or whatever you want to do

or if you know that you always have 'A' and 'B':

import json
json = json.loads('{ "A": { "B": { "C": {"D": "yes"} } } }')

if 'C' in json['A']['B']:
    print(json['A']['B']['C']) #or whatever
Dorison answered 19/9, 2015 at 19:24 Comment(0)
A
3

An quite easy and comfortable way is to use the package python-benedict with full keypath support. Therefore, cast your existing dict d with the function benedict():

d = benedict(d)

Now your dict has full key path support and you can check if the key exists in the pythonic way, using the in operator:

if 'mainsnak.datavalue.value.numeric-id' in d:
    # do something

Please find here the complete documentation.

Ambassador answered 29/7, 2019 at 12:55 Comment(0)
E
2

Use the json module to parse the input. Then within a try statement try to retrieve key "A" from the parsed input then key "B" from the result and then key "C" from that result. If an error gets thrown the nested "C" does not exists

Empurple answered 22/3, 2013 at 23:17 Comment(0)
P
1

Very similar to a SQL isNull or coalesce, Python dict has a get() function that will attempt to return the requested key's value and will return a default value if it is not found. So you can look for each key in turn and return an empty dict to prevent the following get() calls from erroring.

import json
jsondict = json.loads('{ "A": { "B": { "C": {"D": "yes"} } } }')

if jsondict.get("A",{}).get("B",{}).get("C",{}).get("D") == 'yes':
    #do the thing

https://docs.python.org/3/library/stdtypes.html#typesmapping

Passer answered 7/2, 2024 at 19:54 Comment(1)
Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?Mortar
M
0

I used a simple recursive solution:

def check_exists(exp, value):
# For the case that we have an empty element
if exp is None:
    return False

# Check existence of the first key
if value[0] in exp:
    
    # if this is the last key in the list, then no need to look further
    if len(value) == 1:
        return True
    else:
        next_value = value[1:len(value)]
        return check_exists(exp[value[0]], next_value)
else:
    return False

To use this code, just set the nested key in an array of strings, for example:

rc = check_exists(json, ["A", "B", "C", "D"])
Macron answered 18/6, 2021 at 11:26 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.