我想在每个级别展平以下 JSON 并为每个级别创建一个 pandas 数据框,flatten_json
我曾经这样做过,但为此我需要遍历每个级别,从而创建多个嵌套的 for 循环:
{
"metadata": {
"name": "abc",
"time": "2020-04-01"
},
"data": [
{
"identifiers": [
{
"type": "abc",
"scheme": "def",
"value": "123"
},
{
"type": "abc",
"scheme": "def",
"value": "123"
}
],
"name": "qwer",
"type": "abd",
"level1": [
{
"identifiers": [
{
"type": "abc",
"scheme": "def",
"value": "123"
},
{
"type": "abc",
"scheme": "def",
"value": "123"
}
],
"name": "asd",
"type": "abd",
"level2": [
{
"identifiers": [
{
"type": "abc",
"scheme": "def",
"value": "123"
},
{
"type": "abc",
"scheme": "def",
"value": "123"
}
],
"name": "abs",
"type": "abd"
},
{
"identifiers": [
{
"type": "abc",
"scheme": "def",
"value": "123"
},
{
"type": "abc",
"scheme": "def",
"value": "123"
}
],
"name": "abs",
"type": "abd"
}
]
}
]
}
]
}
我正在尝试使用以下代码使用 flatten_json (Python 中的 Flatten JSON)来展平这个 json:
import pandas as pd
import flatten_json as fj
import json
level2 = []
keys = {'data', 'level1', 'level2'}
with open('test_lh.json') as f:
data = json.load(f)
for x in data['data']:
for y in x['level1']:
for z in y['level2']:
dic = fj.flatten(z)
level2.append(dic)
df = pd.DataFrame(level2)
print(df)
输出如下:
identifiers_0_type identifiers_0_scheme identifiers_0_value identifiers_1_type identifiers_1_scheme identifiers_1_value name type
0 abc def 123 abc def 123 abs abd
1 abc def 123 abc def 123 abs abd
我将如何编写一个递归函数来获得相同的输出而不调用 n 个 for 循环?级别可能会下降多个级别。我已经尝试过使用json_normalize
它,但我还需要最终输出中的父级标识符,并且json_normalize
不适用于多个记录路径。