簡體   English   中英

如何更新json嵌套值並保存文件

[英]How to update json nested value and save file

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

我們到了。 這有效

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 應該是

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

因為提名有自己的類別,這些類別沒有經過處理,現在已經處理了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM