【问题标题】:Python: Replace nested dict key's value in entire json whether inside a list or directly a dict [closed]Python:替换整个json中嵌套的dict键的值,无论是在列表中还是直接在dict中[关闭]
【发布时间】:2021-03-21 09:42:08
【问题描述】:

我想将 json 中的值替换为字典的键,它可以直接作为字典出现在 json 中,也可以作为字典出现在另一个列表中,如下所示:

{ 
  "appType": "popper",
  "createdAt": "1970-01-01T00:00:00.000Z",
  "updatedAt": "1970-01-01T00:00:00.000Z",
  "people": [{
            "name": "Vol1",
            "label": "Vol1",
            "peopleInfo": [{
                "name": "ram",
                "age": "2407653459860",
                "id": "1b738651-da9f-4c85-88c1-70dbfe1976681"
            }],
            "itemInfo": {
                "id": "ee763970-51e2-57a5-955c-d72fc3e28a3f",
                "name": "xyz",
                "type": "any",
                "managed": False
            }
        }],
  "itemInfo": [{
            "managed": False,
            "vendorName": "any",
            "serialNumber": "AF-10124"
             }],
}

期望的输出:

{ 
  "appType": "popper",
  "createdAt": "1970-01-01T00:00:00.000Z",
  "updatedAt": "1970-01-01T00:00:00.000Z",
  "peopleInfo": [{
            "name": "Vol1",
            "label": "Vol1",
            "people": [{
                "name": "ram",
                "age": "2407653459860",
                "id": "1b738651-da9f-4c85-88c1-70dbfe1976681"
            }],
            "itemInfo": {
                "id": "ee763970-51e2-57a5-955c-d72fc3e28a3f",
                "name": "xyz",
                "type": "any",
                "managed": True
            }
        }],
  "itemInfo": [{
            "managed": True,
            "vendorName": "any",
            "serialNumber": "AF-10124"
             }],
}

所以在所需的输出中,我想将 ma​​naged 标志更新/替换为 truefalse 用于 itemInfo 直接在 json 和 itemInfopeopleInfo 列表中使用 python。 iteminfo 字典也可以存在于某些不同列表中的整个 json 中。谢谢你的帮助。

我已经写了下面的代码,但不能使它成为一个通用的:

i["details"]["storageSystemsInfo"][0]["managed"] = True

【问题讨论】:

    标签: python json python-3.x list dictionary


    【解决方案1】:

    更新 2:

    按照您的要求,仅更改“itemInfo”字典中的“托管”字段。 (这不是漂亮或干净的代码)

    # Python 3
    def change_this_key_to_true(key, var):
        if hasattr(var,'items'):
            for k, v in var.items(): 
                if k == key:
                    var[k] = True
                if isinstance(v, dict):
                    change_this_key_to_true(key, v)
                elif isinstance(v, list):
                    for d in v:
                        change_this_key_to_true(key, d)
        else:
            if isinstance(var, list):
                for element in var:
                    change_this_key_to_true(key, element)
    
    
    all_item_info_dics = []
    def get_all_values_with_key(key, var):
        if hasattr(var, 'items'):
            for k, v in var.items(): 
                if k == key:
                    all_item_info_dics.append(var[k])
                if isinstance(v, dict):
                    get_all_values_with_key(key, v)
                elif isinstance(v, list):
                    for d in v:
                        get_all_values_with_key(key, d)
    
    get_all_values_with_key("itemInfo", myJson)
    print(all_item_info_dics)
    print("\n")
    change_this_key_to_true("managed", all_item_info_dics)
    print(myJson)
    

    更新: (这是我的第一个答案,花了我一段时间,希望它很好:))

    # Python 3
    def change_this_key_to_true(key, var):
        if hasattr(var,'items'):
            for k, v in var.items():
                if k == key:
                    var[k] = True
                if isinstance(v, dict):
                    change_this_key_to_true(key, v)
                elif isinstance(v, list):
                    for d in v:
                        change_this_key_to_true(key, d)
    
    change_this_key_to_true("managed", myJson)
    print(myJson)
    
    

    遍历复杂的dict/list/“两者的奇怪组合”中的所有字段,并寻找一个名为“managed”的字段并将其更改为True。 基于我的回答: Find all occurrences of a key in nested dictionaries and lists

    原答案:

    x["people"][0]["itemInfo"]["managed"] = True
    x["itemInfo"][0]["managed"] = True
    

    【讨论】:

    • 如果有帮助,请点赞并标记我的回答
    • 这很好,感谢您的帮助,但我正在寻找一个通用解决方案,其中 iteminfo 可以出现在 json 中的任何位置而不是固定键中,所以基本上 peopleInfo 键可以在 json 中不同.
    • 更新后的答案很好,谢谢,但我只需要 itemInfo 字典的托管标志,并非所有托管标志都需要更新。只是 itemInfo dict/list 的一个。并且名称 iteminfo 也可以是任何其他名称:)
    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 2020-07-22
    • 2023-02-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多