【问题标题】:How to store a JSON response from a loop into a dataframe in python如何将来自循环的JSON响应存储到python中的数据框中
【发布时间】:2019-12-08 06:36:06
【问题描述】:

我正在尝试运行具有多个 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)"
          }
        ]
}
}

【问题讨论】:

    标签: python api dataframe


    【解决方案1】:

    现在,您正在循环的每次迭代中覆盖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')
    

    【讨论】:

    • 感谢@JacobIRR,我使用以下代码将附加数据存储到数据帧中 works_data2 = json_normalize(jsonfile2)
    猜你喜欢
    • 2019-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    • 2019-10-22
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多