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 a subkey in a JSON file exists

I want to create a condition to check if a subkey in a JSON file exists:

with open('C:/files/response.json') as json_file:
    data = json.load(json_file)

if 'XMLRESPONSE' in data and data['XMLRESPONSE']['ITEM']:
    print("key exist in JSON data")

else:
    print("Key doesn't exist in JSON data")

input ("Press any key")

But that doesn’t work.

I want to do 2 things:

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

1.-If the [‘ITEM’] not exist, If exists it will continue with the rest of the code.

2.-If not exist the break and exit the code.

Here is an example of the JSON file when exists ITEM:

{
   "XMLRESPONSE": {
      "ITEM": {
         "PARTNUM": "876666",
         "UNITPRICE": "$1.50",
         "ITEMNO": "55667",
         "VENDORITEMNO": "1206613",
         "DESCRIPTION": "tests",
         "VENDORDESCR": "test",
         "ERP": "$1,999.00",
         "REBATEVALUE": "$0.00",
         "REBATEENDDATE": null,
         "ISNONSTOCK": "false",
         "ISFACTORYDIRECT": "false",
         "FREEFRT": "true",
         "RESTRICTED": "false",
         "BRANCHQTY": [
            {
               "BRANCH": "test",
               "QTY": "0",
               "INSTOCKDATE": null
            },
            {
               "BRANCH": "test",
               "QTY": "2",
               "INSTOCKDATE": null
            },
            {
               "BRANCH": "test",
               "QTY": "5",
               "INSTOCKDATE": null
            },
            {
               "BRANCH": "test",
               "QTY": "0",
               "INSTOCKDATE": null
            }
         ],
         "TOTALQTY": "7"
      },
      "STATUS": "success"
   }
}

This is an example of the JSON file when it will trigger the not exist of ITEM:

{"XMLRESPONSE": {"MESSAGE": "Invalid Item Number", "STATUS": "failure"}}

How in the code is needed to inpu the condition?

>Solution :

You can use try-except approach (see handling exceptions doc):

try:
    x = data['XMLRESPONSE']['ITEM']
    print("key exist in JSON data")
except KeyError:
    print("Key doesn't exist in JSON data")
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