使用Python将JSON嵌套到Flattened JSON [英] Nested JSON to Flattened JSON using Python

查看:81
本文介绍了使用Python将JSON嵌套到Flattened JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的JSON文件如下所示-

My JSON file looks like this -

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的代码是-

The code that I have used for flattening JSON is -

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

这是我得到的输出-

但是我正在寻找此输出-

But I am looking for this output -

推荐答案

要实现此目的,您首先需要计算必须执行的步骤.

To achieve this you first need to calculate how much steps you have to do.

请对其进行测试,因为这是一项非常复杂的任务,我不确定100%是否适合您的需求.

Please test it because it is a very complex task i'm not 100% sure if it suites your needs.

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}
#]

这篇关于使用Python将JSON嵌套到Flattened JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆