如何将循环中的JSON响应存储到python中的数据帧中

时间:2019-07-30 19:38:25

标签: python api dataframe

我正在尝试运行具有多个ID的API,并且正在规范化json文件并将其放入数据框。使用我当前的代码,我只能对 jsonfile2 做出一个响应。当我尝试打印json响应时,我会得到所有响应,但是 response.json()在我的代码中不起作用。

for id in ids:
    time.sleep(1)
    url = "https:url/../details/"+str(id)
    querystring = {"API-Token":"Token"}
    headers = {
    'cache-control': "no-cache",
    'postman-token': "111111111111111111111"
    }
    response = requests.request("GET", url.format(id=ids), headers=headers, params=querystring)
#    print(response.json())
    jsonfile2 = response.json()
    works_data2 = json_normalize(jsonfile2, record_path='result')

JSON响应示例

{
  "result": {
    "id": "string",
    "startTime": 0,
    "endTime": 0,
    "tags": [
      {
        "context": "context",
      }
    ],
    "Events": [
      {
        "startTime": 0,
        "endTime": 0,
        "entityId": "string",
        "status": "CLOSED",
        "severities": [
          {
            "context": "context",
            "value": 0,
            "unit": "Bit (bit)"
          }
        ]
}
}

1 个答案:

答案 0 :(得分:2)

现在,您正在循环的每次迭代期间覆盖jsonfile2变量。而是附加到列表呢?

jsonfile2  = []

for id in ids:
    time.sleep(1)
    url = "https:url/../details/"+str(id)
    querystring = {"API-Token":"Token"}
    headers = {
    'cache-control': "no-cache",
    'postman-token': "111111111111111111111"
    }
    response = requests.request("GET", url.format(id=ids), headers=headers, params=querystring)
#    print(response.json())
    jsonfile2.append(response.json())
    works_data2 = json_normalize(jsonfile2, record_path='result')