我有以下json文件:
{"Event": "ev0000001_2019",
"Data": [{
"eventSummary": {
"awards": [{
"awardName": "Foo",
"categories": [{
"categoryName": "Best 1",
"type": ""}],
}]}
}]}
我做了这样一个函数来映射要更改的嵌套值:
def change(category):
name_map = {
"Best 1": "foo1",
"Best 2": "foo2",
"Best 3": "foo3"}
if catName is None:
return ''
else:
if catName in name_map:
catName = name_map[catName]
return catName
现在我需要打开一个json文件并应用这些更改。但是我无法存储更改并保存到新文件中。以下是我正在做的:
with open('./events.json', 'r') as file:
json_file = json.load(file)
#iterate json
for events in json_file:
for all_data in events['Data']:
for awards_names in all_data['eventSummary']['awards']:
for categories_names in awards_names['categories']:
#pass function to the categories:
change(categories_names['categoryName'])
with open('./new_events.json', 'w') as file:
json.dump(json_file, file, indent=4)
我们到了。这很管用
案例的源代码更改
在深入检查了源代码之后,我发现在json结构中有两个地方有类别
所以最终的结果应该是
因为提名有自己的类别,没有经过处理,现在是
相关问题 更多 >
编程相关推荐