Python 如何更新json嵌套值并保存文件
我有以下json文件:Python 如何更新json嵌套值并保存文件,python,json,dictionary,Python,Json,Dictionary,我有以下json文件: {"Event": "ev0000001_2019", "Data": [{ "eventSummary": { "awards": [{ "awardName": "Foo", "categories": [{ "categoryName": "Best 1",
{"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)
我们到了。这很有效
import json
def change(catName):
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
with open('./events.json', 'r') as file:
json_file = json.load(file)
# iterate json
for all_data in json_file['Data']:
for awards_names in all_data['eventSummary']['awards']:
for categories_names in awards_names['categories']:
# pass function to the categories:
categories_names['categoryName'] = change(categories_names['categoryName'])
with open('./new_events.json', 'w') as file:
json.dump(json_file, file, indent=4)
案例的源代码更改
在深入检查您的源代码之后,我发现在json结构中有两个地方有类别
所以我们的决赛应该是
for categories_names in awards_names['categories']:
categories_names['categoryName'] = change(categories_names['categoryName'])
for nomination in categories_names['nominations']:
nomination['categoryName'] = change(nomination['categoryName'])
因为提名有自己的类别,这些类别没有被处理,现在它们被处理了。这会改变值。。。如果我输入:``类别名称['categoryName']=change(类别名称['categoryName'])print(类别名称['categoryName'])``但是更改并没有保存在文件中,也没有使用open('./new_events.json','w')作为文件:json.dump(json_文件,file,indent=4)``或使用``file.seek(0)file.write(json.s dump)(json_file)file.truncate()``整个
change
函数可以替换为name_map
和returnname_map.get(cat_name')的定义
change
函数返回已更改的类别名称,但不将其存储在任何位置。要将其存储在json中,您必须像我那样分配它类别名称['categoryName']=change(类别名称['categoryName'])
我这样做了Alexander。问题是,要更改类别名称['categoryName']
但是如果我再次打印json\u文件
,则categories\u名称['categoryName']
仍然是旧文件。为了保存新文件,我也需要更改json_文件
。哦…最后很简单!感谢@AlexandrShurigin提供的所有帮助,哪些不起作用?这些更改只是没有出现在新文件中吗?你能展示一个没有
的数据示例吗?有更多的data通常是好的。在任何情况下,问题似乎是您没有保存返回的值。