0

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'

2
  • 1
    You can test if a key exists in a dictionary with the in keyword. Optionally you can try to access the key within a try/except KeyError code block. Another way is to use get() on the dictionary Commented Oct 11, 2022 at 12:25
  • You can change the query to if i['fields']['customfield_11723'].get('child'). This returns None if it's not found instead of throwing an error. Commented Oct 11, 2022 at 12:26

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You can even omit the .keys() and it works as well
if "child" in i["fields"]["customfield_11723"] will suffice
1

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)

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.