使用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格式错误吗?或者我的功能是错的?
使用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'}]
将Index.append(x.id)
改为Index.append(x['id'])
这是因为id不是JSON的属性。
没有它,完成这项工作需要一些工作。问题是数据块是一个字符串(有效的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']})