从API读取JSon返回值

时间:2019-06-07 12:57:05

标签: python json

我正在从API的输出中获取以下信息,并且我想读取所有purchaseOrder数据。不太确定如何在此数据上循环。它还在前面带有b'

  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":""
  }
]'

尝试了类似loaded_json = json.load(r.content)之类的操作,但无效。

这是我用来获取响应的代码:

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

2 个答案:

答案 0 :(得分:2)

要获取响应的json,请使用data = response.json()

之后,您可以像普通的listsdicts一样逐步进行操作:

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.

答案 1 :(得分:0)

感谢大家的支持。下一个代码对我有用:

    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'])