Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if key exists is a JSON using Python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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’

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading