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

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

问题描述

我有一个嵌套的JSON,如下所示-

I have a Nested JSON as shown below -

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}]], "i":{"a":5,"b":6}, "j":{} }

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}], "i": {"a": 5, "b": 6}, "j": {} }

我想将其转换为平面JSON文件.

I want to convert this into a flat JSON file.

当前,我正在使用此代码-

Currently, I am using this code -

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

使用此代码时,得到以下输出-

When I am using this code, I get the following output -

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

但是我想要以下输出-

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

这里的代码首先计算JSON中所有列表中元素的最大数量.

The code here first counts the maximum number of elements in all the lists present in the JSON.

推荐答案

data = { "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}], "i": {"a": 5, "b": 6}, "j": {} }

def flatten(dictionary):
    """counts the needed steps from the longest list inside the dictionary"""
    bag = [] # keys to be deleted
    new_dict = dict() # new keys to be added
    for key, value in dictionary.items():
        if type(value) is list:
          bag.append(key)
          for _value in value:
            if type(_value) is dict:  
                for key1, value2 in _value.items():
                    new_key = key + '_' + key1
                    new_dict[new_key] = value2
                    print((new_key, value2))
        else:
            print((key, value))
    for key in bag:
        del dictionary[key]
    for key, value in new_dict.items():
        dictionary[key] = value
    return dictionary

print(flatten(data))

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

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