简体   繁体   中英

Getting KeyError when parsing JSON in Python for following response

TL;DR: Confused on how to parse following JSON response and get the value of [status of 12345 of dynamicValue_GGG of payload] in this case.

Full question: I get the following as (sanitized) response upon hitting a REST API via Python code below:

response = requests.request("POST", url, data=payload, headers=headers).json()

{
    "payload": {
        "name": "asdasdasdasd",
        "dynamicValue_GGG": {
            "12345": {
                "model": "asad",
                "status": "active",
                "subModel1": {
                    "dynamicValue_67890": {
                        "model": "qwerty",
                        "status": "active"
                    },
                "subModel2": {
                    "dynamicValue_33445": {
                        "model": "gghjjj",
                        "status": "active"
                    },
                "subModel3": {
                    "dynamicValue_66778": {
                        "model": "tyutyu",
                        "status": "active"
                    }                   
                }
            }
        },
        "date": "2016-02-04"
    },
    "design": "asdasdWWWsaasdasQ"
}

If I do a type(response['payload']) , it gives me ' dict '.

Now, I'm trying to parse the response above and fetch certain keys and values out of it. The problem is that I'm not able to iterate through using "index" and rather have to specify the "key", but then the response has certain "keys" that are dynamically generated and sent over. For instance, the keys called " dynamicValue_GGG ", " dynamicValue_66778 " etc are not static unlike the " status " key.

I can successfully parse by mentioning like:

print response['payload']['dynamicValue_GGG']['12345'][status]

in which case I get the expected output = ' active '.

However, since I have no control on ' dynamicValue_GGG ', it would work only if I can specify something like this instead:

print response['payload'][0][0][status]

But the above line gives me error: " KeyError: 0 " when the python code is executed.

Is there someway in which I can use the power of both keys as well as index together in this case?

The order of values in a dictionary in Python are random, so you cannot use indexing. You'll have to iterate over all elements, potentially recursive, and test to see if it's the thing you're looking for. For example:

def find_submodels(your_dict):
  for item_key, item_values in your_dict.items():
    if 'status' in item_values:
      print item_key, item_values['status']

    if type(item_values) == dict:
      find_submodels(item_values)

find_submodels(your_dict)

Which would output:

12345 active
dynamicValue_67890 active
dynamicValue_66778 active
dynamicValue_33445 active

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM