python - 使用 Python Pandas 保存到文件时如何正确格式化 JSON?
问题描述
源 JSON 文件如下所示:
{
"Ke1" : [
{
"Key2" : [
{ xxx
}
]
}
]
}
当我使用它更新文件时,df=pd.DataFrame(data) df.to_json(new_file)
它保存为:
{"Key1":{"0":{"Key2":[{ xxx }]}}}
我需要它以原始格式保存。没有 id 0 并且作为 Key2 的列表(第二个括号是[
并且它变成了{
)。如何做到这一点?
解决方案
您可以使用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"}]}]}
推荐阅读
- javascript - FirebaseError:超出配额:如何关闭快照监听器 Firebase
- java - 使用 selenium java 在所有页面中获取公司名称(通过单击下一步按钮)
- deep-learning - 'RuntimeError: mat1 和 mat2 形状不能相乘',我该如何解决?
- python - 如何销毁和重新加载笔记本选项卡
- r - R:数据框中的新列名并将原始列名集成为数据的一部分
- kubernetes - 如何覆盖访问主机名和端口的架构注册表主机
- android - 有没有办法在 Android 键盘上显示“斜体”、“粗体”、“下划线”按钮?
- c - 无法让管道在我的简单 linux shell 中工作
- javascript - Vue 指令打开一个模态
- typescript - 为什么此语句会引发打字稿错误?