gpt4 book ai didi

python - 使用 Python 将 JSON 嵌套到扁平化 JSON

转载 作者:行者123 更新时间:2023-12-01 07:09:12 24 4
gpt4 key购买 nike

我的 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

这是我得到的输出 -

enter image description here

但我正在寻找这个输出 -

enter image description here

最佳答案

要实现这一目标,您首先需要计算需要执行多少步。

请测试它,因为这是一项非常复杂的任务,我不能 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}
#]

关于python - 使用 Python 将 JSON 嵌套到扁平化 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58303668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com