我正在嘗試決議來自 API URL 的嵌套字典,查找 json 回應。我正在嘗試獲取“id”和“symbol”并將其放入串列中,以便稍后將其與另一個串列合并。
我試過了:
try:
response = session.get(url, params=parameters)
data = json.loads(response.text)
for x in data:
print(data['data'][0]['id'])
但它只回傳“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
}
]
}
任何幫助深表感謝。
uj5u.com熱心網友回復:
這是一種方法:
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'])
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/358198.html
上一篇:如何在創建串列時將串列存盤在字典中,然后將其清除,然后用于具有不同值的下一個鍵?
下一篇:將文本中的值轉換為字典
