我有以下json:
{
"request": {
"id": "123",
"url": "/aa/bb/cc",
"method": "GET",
"timestamp": "2018-08-09T08:41:38.432Z"
},
"response": {
"status": {
"code": 200,
"message": "OK"
},
"items": [
{
"id": "aaa",
"name": "w1"
},
{
"id": "bbb",
"name": "w2"
},
{
"id": "ccc",
"name": "w3"
}
]
}
}
我需要遍历items
并打印每个name
。我尝试了以下无效的代码。
response = requests.get(url)
data = json.loads(response.content)
for group in data['response']['items']:
print data['response']['items'][group]['name']
例如,当我将group
替换为0时,我可以访问名字:
data['response']['items'][0]['name']
但是,我不知道该数组中有多少个元素。
答案 0 :(得分:1)
您可以使用 Pandas 模块并调用read_json
函数。
import pandas as pd
df = pd.read_json(your_json_file.json)
for i in df.response['items']:
print(i['name'])
# w1
# w2
# w3
答案 1 :(得分:1)
如Joel所述,在for循环中,
for group in data['response']['items']:
您正在为group
分配data['response']['items']
的值。因此group
包含值:
[
{
"id": "aaa",
"name": "w1"
},
{
"id": "bbb",
"name": "w2"
},
{
"id": "ccc",
"name": "w3"
}
]
所以您要做的就是
print group['name']
答案 2 :(得分:0)
您可以尝试以下方法:
for i in range (0,len(d['response']['items'])):
print(d['response']['items'][i]['name'])
输出:
w1
w2
w3