2

I have a JSON object like this below. Actually huge JSON file, simplified to ask this question.

"header": {
        "headerAttributes": {
            "pageCount": 5,
            "totalCount": 5
        }
    },
"payload": [
    {
        "firstKey": [
                {
                    "nestedKey_1": "1",
                    "nestedKey_2": "2"
                },
                {
                    "nestedKey_3": "3",
                    "nestedKey_4": "4"
                }
            ]
    }
]

Now I wrote below python code to access values inside [].

Total_Orders_Count = json_response ['header']['headerAttributes']['totalCount']
for i in range(0,Total_Orders_Count): 
            dict = json_response ['payload'][i]
            inner_dict = dict ['firstKey'] [0]
            print inner_dict ['nestedKey_1'] + '(' + inner_dict['nestedKey_2'] + ')'

The above code works fine. However, the usage of dict ['firstKey'] [0] doesn't work for values more than 1.

Two Questions. 1. Is there a better way to access Key values inside []. 2. Can we find length of number of values inside []. For this list, length of values under "firstKey" is 2.

Any help is appreciated.

4
  • "the usage of dict ['firstKey'] [0] doesn't work for values more than 1" ? what do you mean? Commented Aug 31, 2017 at 6:50
  • 1
    also don't call your variable dict Commented Aug 31, 2017 at 6:50
  • len(json_response['payload'][i]['firstKey']) Commented Aug 31, 2017 at 6:53
  • @barmar Thanks for this to get the length Commented Sep 2, 2017 at 20:29

2 Answers 2

2

Just loop over the lists directly. There is no need to know a length up front:

for d in json_response ['payload']:
    for inner_dict in d['firstKey']:
        print '{0[nestedKey_1]}({0]nestedKey_2})'.format(inner_dict)

The for <name> in <listobject> loop is a for each construct; no indices are generated. Instead, the loop assigns each element from the list to the target name.

I changed the name dict to d to avoid masking the built-in type. I also used string formatting to put the values from the inner dictionary into a string.

Note that I dropped using the totalCount key altogether. There is no need to look at that value here.

As for finding the length of a list, just use the len() function. Again, there is no need to use that function here, iteration directly over the list removes the need to generate indices up front.

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

Comments

0

In the JSON you provided, there is only one element in the outer list of payload. But the code tries to access the first 5 elements of that list, which don't exist.

Try to avoid using direct access to values in a list like this di['key'], instead use 'di.get('key','default')`, unless you are sure it exists.

To loop through the keys-values and get the length of values under 'firstKey', use the following code:

for payload in json_response.get('payload',[]) :
    # Length of values under firstKey
    print(len(payload.get('firstKey',[])))
    # To access nested Keys
    for i in payload.get('firstKey',[]) :
        for k,v in i.items() :
            print(k,':',v)

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.