如何更新JSON嵌套值并保存文件

时间:2019-12-15 01:49:46

标签: python json dictionary

我有以下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)

1 个答案:

答案 0 :(得分:0)

在这里。可行

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结构中有2个带有类别的地方。

所以最终的目标应该是

                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'])

因为提名有自己的类别,现在尚未处理,现在已经处理了。