如何在关系中用Python解析JSON

2024-09-28 22:34:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有json数据与关系,但我不能循环它

{
    "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

Tags: 数据nameintestimageidjsonfor
3条回答

编辑

正如blender所说,您正在浏览字典键。这将起作用:

改变

for item in json_data['data']

for item in json_data

不过,正如blender提到的,您不需要迭代。你知道吗

我知道了。循环在一篇文章上。你知道吗

myitems = []
for item in json_data['data']['article']:
    myitems.append({
        'title': json_data['data']['name'],
        'image': json_data['data']['image'],
        'article_id': item['id']
    })
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'}]

相关问题 更多 >