Bart
Bart

Reputation: 37

Reading JSon return values from an API

I'm getting below output from an API and I want to read all purchaseOrder data. Not really sure how to loop on this data. Also it comes with b' at the front.

  b'[
   {"purchaseOrder":
    [
     {
      "id":"d01f0f6d-398f-4220-8a9a-44f47beedf04",
      "installationNumber":null,
      "peerId":"308866ba-90cb-47a7-8c73-589c0f355eb7",
      "validFrom":"2019-06-07T12:51:15.000+0000",
      "validTo":"2019-06-07T13:51:15.000+0000",
      "originalQuantity":5,
      "quantity":5,
      "price":5,
      "periodInitial":"2019-06-07T13:00:00.000+0000",
      "periodFinal":"2019-06-07T14:00:00.000+0000"
     }
   ],
   "salesOrder":null,
   "agreement":null,
   "status":""
  }
]'

Have tried things like loaded_json = json.load(r.content) and it didn't work.

This is code I use to get the response:

r = requests.post(url=api_endpoint, data=json.dumps(json_post), headers=headers)

Upvotes: 1

Views: 63

Answers (2)

Bart
Bart

Reputation: 37

Thanks all for support. The next code works for me:

    data = r.json()
    print(json.dumps(data, indent=2))
    for dic in data:
        if 'purchaseOrder' in dic:
            for itemdata in dic['purchaseOrder']:
                for key in itemdata:
                    if key == 'id':
                        print("Id:")
                        print(itemdata['id'])
                        print("Price:")
                        print(itemdata['price']) 

Upvotes: 0

To get the json of a response use data = response.json().

After that you can step through it like normal lists and dicts:

import json
data = r.json()
print(json.dumps(data , indent=2)) # If you want to see the data from the response
for dic in data :
    if 'purchaseOrder' in dic:
        for item in dic['purchaseOrder']:
            # item here is the `dict` for each purchaseOrder (PO).
            print(json.dumps(item, indent=2)) # This will print each item in PO.

Upvotes: 2

Related Questions