在python中展平JSON数据帧



我已经发出了一个API请求,我正在接收下面嵌套格式的JSON(以及我所期望的(。

我不经常需要压平JSON数据&当我这样做时,我只使用Json_normalize。我试过使用json_normalize,但这次没有任何效果。

任何帮助都将不胜感激。

只是为了澄清一下,一旦我发出请求,json数据就会进入一个数据帧。字段应成为列。最终结果是具有列的表:id、字段1、字段2等。

#ACTUAL
[
{
"id": 1000,
"tableName": {
"": {
"field1": null,
"field2": null,
}
}
},
{
"id": 1001,
"tableNameTwo": {
"": {
"field1": null,
"field2": null,
}
}
}
]

#EXPECTED
[
{
"id": 1000,
"field1": null,
"field2": null,
},
{
"id": 1001,
"field1": null,
"field1": null,
},
...
]

更新:下面的代码可以为您工作。

注意:我已将您的输入数据从null修改为None

list = [
{
"id": 1000,
"tableName": {
"": {
"field1": None,
"field2": None,
}
}
},
{
"id": 1001,
"tableNameTwo": {
"": {
"field1": None,
"field2": None,
}
}
}
]
flatList = []
for i in list:
tempDict = {}
for key, value in i.items():
if key.startswith('table'):
for m, n in value[''].items():
tempDict.update({m: n})
else:
tempDict.update({key:value})
flatList.append(tempDict)
print(flatList)

输出:

[
{
'id': 1000,
'field1': None,
'field2': None
},
{
'id': 1001,
'field1': None,
'field2': None
}
]

如果代码中有任何缺陷,contributors请添加注释,答案可以更新。

扁平化json响应几乎总是一种糟糕的做法,例如,如果嵌套对象中存在密钥重复(大多数情况下嵌套对象都有自己的id(,如何解决这种冲突?

然而,如果这个问题不是用于生产,只是做一些家庭作业等。你可以使用以下代码。我在你的例子上测试过:

map = [
{
"id": 1000,
"tablename": {
"": {
"field1": None,
"field2": None,
"field3": None,
"field4": None,
"field5": None,
"field6": None,
"field7": None,
"field8": None,
"field9": None
}
}
}
]
new_map = {}

def flat_json_object(obj):
for k, v in obj.items():
if type(v) is dict:
flat_json_object(v)
else:
new_map[k] = v

def flat_json_array(array):
for obj in array:
flat_json_object(obj)

flat_json_array(map)

我建议如下:

import pandas as pd
your_list = [
{
"id": 1000,
"tablename": {
"tableZero": {
"field0": None,
"field1": None,
"field2": None,
}
}
}
]
df = pd.json_normalize(your_list, sep='_')
print(df.to_dict(orient='records')[0])

这将输出以下语句。

your_result = {
"id": 1000,
"tablename_tableZero_field0": None,
"tablename_tableZero_field1": None,
"tablename_tableZero_field2": None,
}

最新更新