json - 如何使用 Python 使我的 json 文件成为有效的 json 文件
问题描述
我是 Python 新手,我的 Json 文件如下所示:
[
{
"Symbol": "TCS",
"Series": "EQ",
"Date": "04-May-2020",
"Prev Close": 2014.45,
"Open Price": 1966.0,
"High Price": 1966.0,
"Low Price": 1913.65,
"Last Price": 1930.5,
"Close Price": 1930.45,
"Average Price": 1939.3,
"Total Traded Quantity": 3729409.0,
"Turnover": 7232442404.05,
"No. of Trades": 165528.0,
"Deliverable Qty": 1752041.0,
"% Dly Qt to Traded Qty": 46.98
}
]
应该是这样的
{
"tcs":[
{
"Symbol": "TCS",
"Series": "EQ",
"Date": "04-May-2020",
"Prev Close": 2014.45,
"Open Price": 1966.0,
"High Price": 1966.0,
"Low Price": 1913.65,
"Last Price": 1930.5,
"Close Price": 1930.45,
"Average Price": 1939.3,
"Total Traded Quantity": 3729409.0,
"Turnover": 7232442404.05,
"No. of Trades": 165528.0,
"Deliverable Qty": 1752041.0,
"% Dly Qt to Traded Qty": 46.98
}
]
}
如何通过 Python 修改它?
解决方案
如果您的 json 文件名为data.json
,则可以使用此脚本:
import json
with open('data.json', 'r') as f_in:
data = json.load(f_in)
with open('data_out.json', 'w') as f_out:
json.dump({'tcs': data}, f_out, indent=4)
输出将data_out.json
包含以下内容:
{
"tcs": [
{
"Symbol": "TCS",
"Series": "EQ",
"Date": "04-May-2020",
"Prev Close": 2014.45,
"Open Price": 1966.0,
"High Price": 1966.0,
"Low Price": 1913.65,
"Last Price": 1930.5,
"Close Price": 1930.45,
"Average Price": 1939.3,
"Total Traded Quantity": 3729409.0,
"Turnover": 7232442404.05,
"No. of Trades": 165528.0,
"Deliverable Qty": 1752041.0,
"% Dly Qt to Traded Qty": 46.98
}
]
}
推荐阅读
- java - 如何使用 intelliJ 排除通过 Maven 安装的依赖项?
- r - 使用法语口音时 ggsave() 的问题
- spring-data-jpa - 为什么 mock 抛出 nullpointerexception?
- javascript - 将 Google Analytic 事件发送到特定的跟踪代码
- javascript - Youtube 视频不是自动播放,而是什么都不做或显示推荐的视频
- python - 螺旋平面相交
- sql - SQL - 按日期计算库存变动
- javascript - 尝试为节点替换脚本编写正则表达式
- objective-c - Tableview 在下一次重新加载索引更改时崩溃
- powershell - 在 PowerShell 中复制文件进度