[英]Parsing API Json (dictionary) response using python
I'm trying to parse a nested dictionary looking json response from a API URL.我正在尝试解析来自 API URL 的嵌套字典,查找 json 响应。 I'm trying to get the 'id' and 'symbol' and put it in to a list so that I can merge it with another list later.
我正在尝试获取 'id' 和 'symbol' 并将其放入一个列表中,以便稍后将其与另一个列表合并。
I have tried:我试过了:
try:
response = session.get(url, params=parameters)
data = json.loads(response.text)
for x in data:
print(data['data'][0]['id'])
But it just returns "1" two times so i'm guessing the loop is not within the dictionary但它只返回“1”两次,所以我猜这个循环不在字典中
print(type(data))
<class 'dict'>
I would need a loop to get every iteration of 'id' and 'symbol' and append it to a list.我需要一个循环来获取 '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
}
]
}
Any help is much appreciated.任何帮助深表感谢。
response = session.get(url, params=parameters)
data = json.loads(response.text)
for x in data:
print(x['data'][0]['id'])
Another way:其它的办法:
response = session.get(url, params=parameters)
data = json.loads(response.text)
for x in data["data"]:
print(x['id'])
Just beautiful way:只是美丽的方式:
response = session.get(url, params=parameters).json()
for x in response:
print(x['data'][0]['id'])
Beautiful way if you need to use response data in other way:如果您需要以其他方式使用响应数据,那么漂亮的方式:
response = session.get(url, params=parameters)
for x in response.json():
print(x['data'][0]['id'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.