使用 python 解析 API Json(字典)响应

Parsing API Json (dictionary) response using python

我正在尝试解析嵌套字典,查找 json 来自 API URL 的响应。我正在尝试获取 'id' 和 'symbol' 并将其放入列表中,以便稍后将其与另一个列表合并。

我试过:

try:
response = session.get(url, params=parameters)
data = json.loads(response.text)
for x in data:
print(data['data'][0]['id'])

但它只是 returns “1” 两次所以我猜循环不在字典中

print(type(data))
<class 'dict'>

我需要一个循环来获取 'id' 和 'symbol' 的每次迭代并将其附加到列表中。

   {
  "status": {
    "timestamp": "2021-11-13T20:50:29.375Z",
    "error_code": 0,
    "error_message": null,
    "elapsed": 11,
    "credit_count": 1,
    "notice": null
  },
  "data": [
    {
      "id": 1,
      "name": "Bitcoin",
      "symbol": "BTC",
      "slug": "bitcoin",
      "rank": 1,
      "is_active": 1,
      "first_historical_data": "2013-04-28T18:47:21.000Z",
      "last_historical_data": "2021-11-13T20:39:02.000Z",
      "platform": null
    },
    {
      "id": 2,
      "name": "Litecoin",
      "symbol": "LTC",
      "slug": "litecoin",
      "rank": 14,
      "is_active": 1,
      "first_historical_data": "2013-04-28T18:47:22.000Z",
      "last_historical_data": "2021-11-13T20:39:02.000Z",
      "platform": null
    },
    {
      "id": 3,
      "name": "Namecoin",
      "symbol": "NMC",
      "slug": "namecoin",
      "rank": 778,
      "is_active": 1,
      "first_historical_data": "2013-04-28T18:47:22.000Z",
      "last_historical_data": "2021-11-13T20:39:02.000Z",
      "platform": null
    },
    {
      "id": 4,
      "name": "Terracoin",
      "symbol": "TRC",
      "slug": "terracoin",
      "rank": 2062,
      "is_active": 1,
      "first_historical_data": "2013-04-28T18:47:22.000Z",
      "last_historical_data": "2021-11-13T20:39:03.000Z",
      "platform": null
    },
    {
      "id": 5,
      "name": "Peercoin",
      "symbol": "PPC",
      "slug": "peercoin",
      "rank": 707,
      "is_active": 1,
      "first_historical_data": "2013-04-28T18:47:23.000Z",
      "last_historical_data": "2021-11-13T20:39:02.000Z",
      "platform": null
    }
  ]
}

非常感谢任何帮助。

这是一种方法:

response = session.get(url, params=parameters)
data = json.loads(response.text)
for x in data:
    print(x['data'][0]['id'])

这是另一种方式:

response = session.get(url, params=parameters)
data = json.loads(response.text)
for x in data["data"]:
    print(x['id'])

这是一个绝妙的方法:

response = session.get(url, params=parameters).json()
for x in response:
    print(x['data'][0]['id'])

最后,如果您需要以其他方式使用响应数据,还有一个漂亮的方法:

response = session.get(url, params=parameters)
for x in response.json():
    print(x['data'][0]['id'])