所以我正在使用 API 提取一些 json 数据,它最初看起来像这样:
{
"result": {
"elements": [
{
"id": "SV_3s0FmbrNancSmsB",
"name": "Test Survey",
"ownerId": "sdfsdfasdf",
"lastModified": "2016-08-09T21:33:27Z",
"isActive": false
},
{
"id": "SV_dgJOVyJvwZR0593",
"name": "Test Survey",
"ownerId": "sdfdsfsdfs",
"lastModified": "2016-08-04T17:53:37Z",
"isActive": true
}
],
"nextPage": null
},
"meta": {
"httpStatus": "200 - OK"
}
}
所以我想使用 Python 提取此 JSON 中的所有 ID,这是我的代码:
url = "random.com"
headers = {
'x-api-token': "dsfsdagdfa"
}
response = requests.get(url, headers=headers)
data = json.loads(response.text)
id_0 = data['result']['elements'][0]['id']
print(id_0)
这基本上只会打印创建的数组中的第一个 Id。我该怎么做才能获得所有 ID?
最佳答案
你可以使用这个 oneliner:
ids = [element['id'] for element in data['result']['elements']]
关于python - 如何获取 python 数组中的所有 "ids",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39006669/