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"} } } }

5 Answers 5

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

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

1 Comment

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?
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"])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.