【问题标题】:Nested JSON to Flattened JSON using Python使用 Python 将 JSON 嵌套到扁平化 JSON
【发布时间】:2019-10-09 11:59:38
【问题描述】:

我的 JSON 文件如下所示 -

sample4 = {
        "a": 1,
        "b": 2, 
        "c": 3,
        "d": [{"a": 5, "b": 6}, {"a": 7, "b": 8}],
        "e": [{"a": 1}, {"a": 2}],
        "f": 9,
        "g": [{"a": 5, "b": 6}, {"a": 7, "b": 8}]
    }

我用于扁平化 JSON 的代码是 -

def flatten_json(y):
    out = {}

def no_mas(x, name=''):
    out[name[:-1]] = x

def flatten(x, name=''):
    if type(x) is dict:
        for a in x:
            if a == 'MetaDataList':
                no_mas(x[a], name + a + '_')
            else:
                flatten(x[a], name + a + '_')
    elif type(x) is list:
        i = 0
        for a in x:
            flatten(a, name)
            i += 1
    else:
        out[name[:-1]] = x

    flatten(y)
    return out

这是我得到的输出 -

但我正在寻找这个输出 -

【问题讨论】:

  • 请多解释一下代码应该做什么。 sample4 的键可以是“MetaDataList”吗? flatten 的输出究竟应该是什么样子?
  • 代码在嵌套的 JSON 文件中,输出应该是扁平化的 JSON 文件。扁平化 JSON 的输出应如下所示 - {{"a": 1, "b": 2, "c": 3,"d_a": 5, "d_b": 6, "e_a": 1, "f" :9,“g_a”:5,“g_b”:6},{“a”:1,“b”:2,“c”:3,“d_a”:7,“d_b”:8,“e_a” : 2, "f":9, "g_a":7, "g_b":8}}
  • 这不是有效的 JSON。外面的{}应该是[],也就是一个列表吗?
  • 应该是[]。对不起。

标签: python json python-3.x


【解决方案1】:

要实现这一点,您首先需要计算您必须执行的步骤。

请测试它,因为这是一项非常复杂的任务,我不能 100% 确定它是否适合您的需求。

sample4 = {
        "a": 1,
        "b": 2, 
        "c": 3,
        "d": [{"a": 5, "b": 6}, {"a": 7, "b": 8}],
        "e": [{"a": 1}, {"a": 2}],
        "f": 9,
        "g": [{"a": 5, "b": 6}, {"a": 7, "b": 8}]
    }

def count_steps(dictionary):
    """counts the needed steps from the longest list inside the dictionary"""
    return max((len(value) for value in dictionary.values() if isinstance(value, list)))

def flatten(dictionary, name=''):
    steps = count_steps(dictionary)
    return_out = []
    for step in range(0, steps):
        out = {}
        for key, value in dictionary.items():
            if isinstance(value, list):
                for key_inner, value_inner in value[step].items():
                    combined_key = key + '_' + key_inner
                    if combined_key not in out:
                        out[combined_key] = []
                    out[combined_key] = value_inner
            else:
                out[key] = value
        return_out.append(out)
    return return_out

print(flatten(sample4))

#[
# {'a': 1, 'b': 2, 'c': 3, 'd_a': 5, 'd_b': 6, 'e_a': 1, 'f': 9, 'g_a': 5, 'g_b': 6},
# {'a': 1, 'b': 2, 'c': 3, 'd_a': 7, 'd_b': 8, 'e_a': 2, 'f': 9, 'g_a': 7, 'g_b': 8}
#]

【讨论】:

    猜你喜欢
    • 2019-04-24
    • 2017-09-18
    • 1970-01-01
    • 2021-11-19
    • 2023-04-03
    • 2019-04-11
    • 2021-08-21
    • 1970-01-01
    • 2018-08-27
    相关资源
    最近更新 更多