Check if key exists is a JSON using Python

Question:

I am trying to check if a key exists in Json file.
the key name is child and in some cases it exists and in some it doesn’t.
example 1 – key doesn’t exists:

"customfield_11723": {
    "self": "https://ies-data-jira.ies.data.com/rest/api/2/custom/16110",
    "value": "DATA_MDM",
    "id": "16110",
    "disabled": false
},

exempla 2 – key exists:

"customfield_11723": {
                "self": "https://ies-data-jira.ies.data.com/rest/api/2/customFieldOption/16118",
                "value": "DATA_QM",
                "id": "16118",
                "disabled": false,
                "child": {
                    "self": "https://ies-data-jira.ies.data.com/rest/api/2//16124",
                    "value": "Installation",
                    "id": "16124",
                    "disabled": false
                }

The key path in the json file is [‘issues][‘fields’][‘customfield_11723’][‘child’]
My code looks like this:

for i in todos['issues']:


    if i['fields']['customfield_11723']['child'] in i['fields']['customfield_11723']:
       print("True"

when I run this on case where the ‘child’ doesnt exist the exception is given on ketError:’child’

Asked By: Nir Eyal

||

Answers:

Check the existence of the key by using the keys() dict method:

if "child" in i["fields"]["customfield_11723"].keys():
    print(True)

The keys() method returns a list of all the keys in the dictionary.

Answered By: frab

in your specific case you would need to ask:

# .keys() is optional but more explicit
if "child" in i['fields']['customfield_11723'].keys():
    print("True")

Personally, I’d try to use the walrus operator in combination with the dict.get() method in such situations:

if child := i['fields']['customfield_11723'].get("child"):
    print(child)
Answered By: pkeilbach
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.