如何更新json嵌套值并保存fi

2024-09-30 01:20:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 文件nameinjsonmapfordatanames
1条回答
网友
1楼 · 发布于 2024-09-30 01:20:44

我们到了。这很管用

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

因为提名有自己的类别,没有经过处理,现在是

相关问题 更多 >

    热门问题