在一个大表中获取JSON响应

5n0oy7gb  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(124)

我目前正在使用Python创建管道,这真的很有趣,但目前我真的卡住了:我试图在一个大表中递归地获得JSON响应。
我特别想把这句话讲得通:不要命名所有部分,但也可以在其他json文件上使用相同的脚本。
你们有什么建议吗(我还是很绿色)。
举个json例子:

{
"area": {
    "id": 2072,
},
"competition": {
    "id": 2021,
},
"season": {
    "id": 733,
},
"standings": [
    {
        "type": "TOTAL",
        "table": [
            {
                "position": 1,
                "team": {
                    "id": 65,
                    "name": "Manchester City FC",
                },
                "playedGames": 37,
            },
            {
                "position": 2,
                "team": {
                    "id": 64,
                    "name": "Liverpool FC",
                },
                "playedGames": 36,
            }
        ]
    },
    {
        "type": "HOME",
        "table": [
            {
                "position": 1,
                "team": {
                    "id": 64,
                    "name": "Liverpool FC",
                },
                "playedGames": 18,
            },
            {
                "position": 2,
                "team": {
                    "id": 65,
                    "name": "Manchester City FC",
                },
                "playedGames": 18,
            }
        ]
    },
]

}
在这种情况下,我想要的输出是:

我目前使用的代码:

import pandas as pd

def flatten_json(json_data, prefix=''):
flattened_data = {}
for key, value in json_data.items():
    if isinstance(value, dict):
        flattened_data.update(flatten_json(value, prefix + key + '.'))
    elif isinstance(value, list):
        for i, item in enumerate(value):
            flattened_data.update(flatten_json(item, prefix + key + '.' + str(i) + '.'))
    else:
        flattened_data[prefix + key] = value
return flattened_data


flattened_data = flatten_json(json_data)
df = pd.DataFrame([flattened_data])
df = df.rename(columns=lambda x: '.'.join(x.split('.')[-2:]) if '.' in x else x)
df = df[df.columns.dropna()]
print(df)
k97glaaz

k97glaaz1#

你可以json_normalize你的数据,然后做一点 * 后处理 *:

df = (
    pd.json_normalize(
        json_data, ["standings", "table"],
        meta=[["standings", "type"]], record_prefix="standings.table.")
    .assign(**{f"{k}.id": json_data[k]["id"]
               for k in ("area", "competition", "season")})
)

输出:
| standings.table.position | standings.table.playedGames |standings.table.team.id|standings.table.team.name| standings.type |area.id|competition.id|season.id|
| - -----|- -----|- -----|- -----|- -----|- -----|- -----|- -----|
| 1|三十七|六十五|曼城足球俱乐部|总计|2072|二〇二一|七三三|
| 2|三十六|六十四|利物浦足球俱乐部|总计|2072|二〇二一|七三三|
| 1|十八岁|六十四|利物浦足球俱乐部|关于我们|2072|二〇二一|七三三|
| 2|十八岁|六十五|曼城足球俱乐部|关于我们|2072|二〇二一|七三三|

相关问题