Nancy Moore
Nancy Moore

Reputation: 2470

how to correctly print json response using python

I have json arrays as follows

payload.json

{"provision":"provision section 1",
       "subsets": [{"item":"milk"},{"payments": [{"price": "170 usd"}]},
                   {"item":"sugar"},{"payments": [{"price": "70 usd"}]}, 
                   {"item":"tea"},{"payments": [{"price": "90 usd"}]}]}

Here is the code am using to get the json response

import json
import requests
r = requests.get('http://localhost/payload.json')
stat=r.status_code
head=r.headers['content-type']
encode=r.encoding
texting=r.text
result=r.json()

print(stat)
print(head)
print(texting)
print(result)

I can successfully get the results in json

My requirements: How do I successfully loops to print out values for Provisions, item and price. If i try something like print(result.provision), it will display error dict object has no attribute provision

Upvotes: 0

Views: 80

Answers (2)

DirtyBit
DirtyBit

Reputation: 16772

The error you got:

dict object has no attribute provision

The reason:

Since dict does not have any attribute as such.

Also:

As stated already by @RemcoGerlich, now that it is a dict you may access its elemenets by:

result = {"provision":"provision section 1",
       "subsets": [{"item":"milk"},{"payments": [{"price": "170 usd"}]},
                   {"item":"sugar"},{"payments": [{"price": "70 usd"}]},
                   {"item":"tea"},{"payments": [{"price": "90 usd"}]}]}

print(result['provision'])
print(result['subsets'])

OR

for k,v in result.items():
    print(k,v)

OUTPUT:

provision provision section 1
subsets [{'item': 'milk'}, {'payments': [{'price': '170 usd'}]}, {'item': 'sugar'}, {'payments': [{'price': '70 usd'}]}, {'item': 'tea'}, {'payments': [{'price': '90 usd'}]}]

EDIT:

Since the dict_ has elements with lists:

result = {"provision":"provision section 1",
       "subsets": [
           {"item":"milk"},
           {"payments": [{"price": "170 usd"}]},
           {"item":"sugar"},
           {"payments": [{"price": "70 usd"}]},
           {"item":"tea"},
           {"payments": [{"price": "90 usd"}]}
       ]
          }

Let's say you want to get the first element inside subsets:

print(result.get('subsets')[0])   # {'item': 'milk'}

Where as;

print(result.get('subsets')[0].values())    # dict_values(['milk'])

Upvotes: 0

RemcoGerlich
RemcoGerlich

Reputation: 31250

At that point you don't have a JSON object anymore, JSON was simply the way it was transported between the server and you; r.json() translates it into a Python dictionary.

You access keys of a Python dictionary with e.g. result['provision'] and you can print that.

That said, as you also tagged this with Django, inside a Django template you would still use result.provision; that tries several things until it gets a result it can print, including the case where result is a dictionary and provision a key of it.

Upvotes: 2

Related Questions