首页 > 解决方案 > 从python中的json文件中提取元素

问题描述

使用 Python,我有以下 JSON 结构:

[
    {
        "id": 1,
        "data": "{'id': '1', 'title': 'title of id 1', 'foo': 'bar', 'fooo': ['bar', 'baar']}"
    },
    {
        "id": 2,
        "data": "{'id': '2', 'title': 'title of id 2', 'foo': 'bar', 'fooo': ['bar', 'baar']}"
    },
    {
        "id": 3,
        "data": "{'id': '3', 'title': 'title of id 3', 'foo': 'bar', 'fooo': ['bar', 'baar']}"
    }
]

我想将第一个数据元素存储在一个新的 .json 中,例如

[
{
 1 : 'title of 1',
 2 : 'title of 2',
...
}
]

现在,我尝试了很多东西,最近的是:

Index = []
for x in checklists:
    item = {"id": x}
    Index.append(x)
return Index

或者

Index = []
for x in checklists:
    x = json.dumps(x)
    Index.append(x.id)
return Index

但是每次我尝试执行它时,我都会收到相同的错误:

AttributeError: 'str' object has no attribute 'id'

这引出了我的问题。我的 json 格式是否错误?还是我的功能错了?

标签: pythonjson

解决方案


没有 ast 需要一些工作才能完成这项工作。问题是数据块是一个字符串(这是有效的 json),但不是你想要的。

您想要的是要格式化的数据中的数据 comme ca:

{
    "id": 1,
    "data": {"id": "1", "title": "title of id 1", "foo": "bar"}
}

现在,当您遍历每个数据块(其中 json_array 是您的完整 json)时:

for json_block in json_array:
    temp = json_block['data']
    title = (temp['title'])

或者:

for json_block in json_array:
    title= json_block['data']['title']

您现在可以轻松地将每个标题添加到新数组中:

    index_list.append({'id': title})

整个方法看起来像:

def create_new_json():
    index_list = []
    for json_block in json_array:
        index_list.append({json_block ['id']: json_block ['data']['title']})

推荐阅读