从python中的json文件中提取元素
使用Python,我有以下JSON结构:从python中的json文件中提取元素,python,json,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': ['
[
{
"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']}"
}
]
我想将数据的第一个to元素存储在一个新的类似.json的文件中
[
{
1 : 'title of 1',
2 : 'title of 2',
...
}
]
现在,我尝试了很多东西,最近的是:
Index = []
for x in checklists:
item = {"id": x}
Index.append(x)
return Index
或
但每次我尝试执行它时,都会收到相同的错误:
这就引出了我的问题。我的json格式是否错误?还是我的函数错了?更改Index.append(x.id)
到Index.append(x['id'))
这是因为id不是JSON的属性。使用
ast
模块
Ex:
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'}]
输出:
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'}]
如果没有ast,这将需要一些工作才能完成。问题是数据块是一个字符串(有效的json),但不是您想要的 您需要将数据中的数据格式化为comme ca:
{
"id": 1,
"data": {"id": "1", "title": "title of id 1", "foo": "bar"}
}
现在,当您在每个数据块(其中json_数组是完整的json)上循环时:
或:
现在,您可以轻松地将每个标题添加到新数组中:
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']})
两个答案都返回类型错误:字符串索引必须是整数
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']})