Check if a subkey in a JSON file exists

Question:

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:

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?

Asked By: Alex Co

||

Answers:

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")
Answered By: Guru Stron
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.