如何将嵌套的json转换为以下格式?

2024-04-18 23:40:02 发布

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

如何将以下嵌套的json转换为所需的格式?你知道吗

嵌套JSON:

{
        "node":[
            {
                "item_1":"value_11",
                "item_2":"value_12",
                "item_3":"value_13",
                "item_4":["sub_value_14", "sub_value_15"],
                "item_5":{
                    "sub_item_1":"sub_item_value_11",
                    "sub_item_2":["sub_item_value_12", "sub_item_value_13"]
                }
            },
            {
                "item_1":"value_21",
                "item_2":"value_22",
                "item_4":["sub_value_24", "sub_value_25"],
                "item_5":{
                    "sub_item_1":"sub_item_value_21",
                    "sub_item_2":["sub_item_value_22", "sub_item_value_23"]
                }
            }
        ]
    }

预期输出:

{
  'node_item_1': ['value_11','value_21'],
  'node_item_2': ['value_12','value_22'],
  'node_item_3': 'value_13',
  'node_item_4': ['sub_value_14','sub_value_15','sub_value_24','sub_value_25'],
  'node_item_5_sub_item_1': ['sub_item_value_11','sub_item_value_21'],
  'node_item_5_sub_item_2': ['sub_item_value_12','sub_item_value_13','sub_item_value_22', 'sub_item_value_23']
}

我尝试使用https://towardsdatascience.com/how-to-flatten-deeply-nested-json-objects-in-non-recursive-elegant-python-55f96533103d?gi=c5b18e648c0c压平JSON,然后尝试以上述格式获取JSON。但我做不到。你知道吗


Tags: tohttpscomnodejsonobjectsvalue格式
1条回答
网友
1楼 · 发布于 2024-04-18 23:40:02
  • 我只想从,这将是丑陋的和非pythonic,但它只是一样丑陋的json文件
  • 它会根据请求从给定的数据返回新的dict
    • 除此之外,所有values都将是lists
  • 创建两个函数更容易:
    • make_dict_keys创建新的dict,值为空lists
    • fill_dict填充空的dict
  • 无论有多少keysitem_1处于同一级别,此代码都将工作,并将接受与item_5相同形式的任意数量的键。你知道吗
  • 它将不适用于dicts,因为值低于sub_item_x

make_dict_keys

def make_dict_keys(file: dict) -> dict:
    """
    Given ugly json file, create a flat empty dict of lists.
    Keys of the dict will be the keys of the json file, except
    in the case that a value is a dict.  In that case, the new key
    added to test will be in the form key2_key3
    """
    test = dict()

    for key1, value1 in file.items():
        for x in value1:
            for key2, value2 in x.items():
                if type(value2) != dict:
                    test[key2] = []
                else:
                    for key3 in value2.keys():
                        test[f'{key2}_{key3}'] = []
    return test

fill_dict

def fill_dict(file: dict) -> dict:
    """
    Given ugly json file, call make_dict_keys to get
    empty dict.
    Fill new_dict from the values of the json file
    """

    new_dict = make_dict_keys(file)

    for key1, value1 in file.items():
        for x in value1:
            for key2, value2 in x.items():
                if type(value2) == list:
                    new_dict[key2].extend(value2)
                elif type(value2) == str:
                    new_dict[key2].append(value2)
                else:
                    for key3, value3 in value2.items():
                        if type(value3) == list:
                            new_dict[f'{key2}_{key3}'].extend(value3)
                        else:
                            new_dict[f'{key2}_{key3}'].append(value3)
    return new_dict

输出:

from pprint import pprint as pp

blah = fill_dict(data)  # where data = that nested dict
pp(blah)

{'item_1': ['value_11', 'value_21'],
 'item_2': ['value_12', 'value_22'],
 'item_3': ['value_13'],
 'item_4': ['sub_value_14', 'sub_value_15', 'sub_value_24', 'sub_value_25'],
 'item_5_sub_item_1': ['sub_item_value_11', 'sub_item_value_21'],
 'item_5_sub_item_2': ['sub_item_value_12',
                       'sub_item_value_13',
                       'sub_item_value_22',
                       'sub_item_value_23']}
  • 毫无疑问,有人可以做得更好,如果他们想投资的时间。
    • recursion是一条可能的途径

相关问题 更多 >