从python中的json文件中提取元素

时间:2018-08-07 14:46:59

标签: 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格式错误吗?还是我的功能错了?

3 个答案:

答案 0 :(得分:0)

Index.append(x.id)更改为Index.append(x['id'])

这是因为id不是JSON的属性。

答案 1 :(得分:0)

使用ast模块。

例如:

import ast
index_list = []
for x in checklists:
    val = ast.literal_eval(x["data"])
    index_list.append({x['id']: val["title"]})
return index_list

输出:

[{1: 'title of id 1'}, {2: 'title of id 2'}, {3: 'title of id 3'}]

答案 2 :(得分:0)

如果没有ast,则需要花一些工夫才能完成。问题在于数据块是一个字符串(有效的json),但不是您想要的。

您想要的是要格式化的数据,以逗号分隔:

{
    "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']})