首页 > 解决方案 > 使用 Python Pandas 保存到文件时如何正确格式化 JSON?

问题描述

源 JSON 文件如下所示:

{
 "Ke1" : [
   {
    "Key2" : [
   { xxx
}
]
}
]
}

当我使用它更新文件时,df=pd.DataFrame(data) df.to_json(new_file)它保存为:

{"Key1":{"0":{"Key2":[{ xxx }]}}}

我需要它以原始格式保存。没有 id 0 并且作为 Key2 的列表(第二个括号是[并且它变成了{)。如何做到这一点?

标签: pythonjsonpandas

解决方案


您可以使用json_normalize

import pandas as pd

data={
    "Ke1": [{
            "Key2": [{
                    "we": "wewe"
                }
            ]
        }
    ]
}
df=pd.json_normalize(data)
df.to_json(orient="records", lines=True)

输出:

{"Ke1":[{"Key2":[{"we":"wewe"}]}]}

推荐阅读