Artem Yevtushenko Artem Yevtushenko -4 years ago 87
Python Question

How to select x level deep JSON data with Python

I am trying to select data with python from what I believe is formatted in JSON. I am using this for loop to select the data as so.

for line_item in response['response']:
print(line_item['name'] + ', ' + line_item['orderId'])


But how would I also select impressionsDelivered so the output is 1234?

(LineItem){
orderId = 123456
name = "fooname"
stats = (Stats){
impressionsDelivered = 1234
clicksDelivered = 1234
}

Answer Source

Let's say you have this json called response (to use your example):

response = {
          "response":    [   # start of a list of elements
                   {         # start of the 1st element
          "orderId" : 123456,
          "name" : "fooname",
          "stats" : {
                    "impressionsDelivered" : 1234,
                    "clicksDelivered" : 1234
                    }},      # end of the 1st element
                    {        # start of the 2nd element
          "orderId" : 1234565,
          "name" : "fooname2",
          "stats" : {
                    "impressionsDelivered" : 12345,
                    "clicksDelivered" : 12345
                    }}      # end of the second element
                          ] # end of the list
             }

A json is a dictionary like format with keys and values its written: {key:value}

and a value can be itself compose of keys and values example: key: {key2:value2} , {key2:value2} being the value of key

How to access them: You access a dictionary by the keys

in the json above, if I want to access all the values of response:

print( response["response"] )

if you want a deep access to the next element, which is orderId, notice the bracket opening '[' which tells you a list starts:

print( response["response"][0] ) # first element of the list
print( response["response"][0]["orderId"] ) # access orderId

You access a dictionary by its key and a list by its index

Tip: Use Ipython and paste this code to practice

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download