如何在2维中展平JSON,只能在1维中展平

2024-10-01 07:39:43 发布

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

我们正在尝试将一个json展平为二维,但是我们只能用下面的函数展平为一维,这个函数返回二维的json,但是我们需要一个json数组,您可以将一个数行(二维)的数据帧

import json
from itertools import chain, starmap

def flatten_json(dictionary):
    def unpack(parent_key, parent_value, sep="_"):
        if isinstance(parent_value, dict):
            for key, value in parent_value.items():
                temp1 = parent_key + sep + key
                yield temp1, value
        elif isinstance(parent_value, list):
            i = 0
            for value in parent_value:
                temp2 = parent_key + sep + str(i)
                i += 1
                yield temp2, value
        else:
            yield parent_key, parent_value
    while True:
        dictionary = dict(chain.from_iterable(starmap(unpack, dictionary.items())))
        if not any(isinstance(value, dict) for value in dictionary.values()) and \
                not any(isinstance(value, list) for value in dictionary.values()):
            break
    return dictionary

j=json.loads('{"id":{"oid":"XXXXX"},"class":"YYYYY","version":"1","array": [{"key1" :  "value1"}, {"key2" :  "value2"}, {"key3" :  "value3"}, {"key4" :  "value4"}],"name":"GVASDAD","code":"V","level":6,"value":"0"}')


print(flatten_json(j))

Out[11]: 
{'id_oid': 'XXXXX',
 'class': 'YYYYY',
 'version': '1',
 'array_0_key1': 'value1',
 'array_1_key2': 'value2',
 'array_2_key3': 'value3',
 'array_3_key4': 'value4',
 'name': 'GVASDAD',
 'code': 'V',
 'level': 6,
 'value': '0'}

我想通过以下方式得到一个json数组:

[{'id_oid': 'XXXXX',
'class': 'YYYYY',
'version': '1',
'array': 'value1',
'name': 'GVASDAD',
'code': 'V',
'level': 6,
'value': '0'},
{'id_oid': 'XXXXX',
'class': 'YYYYY',
'version': '1',
'array': 'value2',
'name': 'GVASDAD',
'code': 'V',
'level': 6,
'value': '0'},
{'id_oid': 'XXXXX',
'class': 'YYYYY',
'version': '1',
'array': 'value3',
'name': 'GVASDAD',
'code': 'V',
'level': 6,
'value': '0'},
{'id_oid': 'XXXXX',
'class': 'YYYYY',
'version': '1',
'array': 'value4',
'name': 'GVASDAD',
'code': 'V',
'level': 6,
'value': '0'}]

任何建议都会有帮助

提前感谢大家


Tags: keynameidjsondictionaryvalueversioncode