如何在关系中使用Python解析JSON
我有json数据与关系,但我不能循环它如何在关系中使用Python解析JSON,python,json,loops,Python,Json,Loops,我有json数据与关系,但我不能循环它 { "data": { "id": 2, "name": "My TEST", "image": "1.jpg", "article": [ { "id": 1, "name": "TEST" } ] } } 我试着像 myitems = [] fo
{
"data": {
"id": 2,
"name": "My TEST",
"image": "1.jpg",
"article": [
{
"id": 1,
"name": "TEST"
}
]
}
}
我试着像
myitems = []
for item in json_data['data']:
myitems.append({
'title': item['name'],
'image': item['image'],
'article_id': item['article'][0]['id']
})
它告诉我
TypeError: string indices must be integers
编辑
正如blender所评论的,您正在运行字典键。这将有助于:
改变
for item in json_data['data']
到
但是,正如blender提到的,您不需要迭代。我明白了。循环在一篇文章上
d = {
"data": {
"id": 2,
"name": "My TEST",
"image": "1.jpg",
"article": [
{
"id": 1,
"name": "TEST"
}
]
}
}
myitems=[{
'title': d["data"]['name'],
'image': d["data"]['image'],
'article_id': d["data"]['article'][0]['id']
}]
print myitems
[{'image': '1.jpg', 'article_id': 1, 'title': 'My TEST'}]
myitems = []
for item in json_data['data']['article']:
myitems.append({
'title': json_data['data']['name'],
'image': json_data['data']['image'],
'article_id': item['id']
})
json_data['data']是一个字典。您不需要对其进行迭代。请打印json_数据。我想当你这么做的时候,你会发现问题所在。我知道了,因为我是python新手。
myitems = []
for item in json_data['data']['article']:
myitems.append({
'title': json_data['data']['name'],
'image': json_data['data']['image'],
'article_id': item['id']
})