python - 在 python 中更改 .json 文件
问题描述
我有以下 .json 文件,如下所示:
[
{
"2004": "0",
"2005": "0",
"2006": "0",
},
{
"2004": "0",
"2005": "0",
"2006": "0",
},
{
"2013": "0",
"2014": "0",
"2015": "--",
}
]
如何在 python 中获取如下 .json 文件,如下所示:
{
"Countries": [
{
"2004": "0",
"2005": "0",
"2006": "0"
},
{
"2004": "0",
"2005": "0",
"2006": "0"
},
{
"2013": "0",
"2014": "0",
"2015": "--"
}
]
}
解决方案
对于您use_files = True
在脚本开头使用文件更改为的情况,并设置正确的文件名而不是'input.json'
and 'output.json'
。
import json
use_files = False
inp_fname, out_fname = 'input.json', 'output.json'
if not use_files:
text = """
[
{
"2004": "0",
"2005": "0",
"2006": "0"
},
{
"2004": "0",
"2005": "0",
"2006": "0"
},
{
"2013": "0",
"2014": "0",
"2015": "--"
}
]
"""
if use_files:
with open(inp_fname, 'r', encoding = 'utf-8') as f:
text = f.read()
obj = json.loads(text)
obj = {'Countries': obj}
rtext = json.dumps(obj, indent = 4, ensure_ascii = False)
if use_files:
with open(out_fname, 'w', encoding = 'utf-8') as f:
f.write(rtext)
else:
print(rtext)
代码输出:
{
"Countries": [
{
"2004": "0",
"2005": "0",
"2006": "0"
},
{
"2004": "0",
"2005": "0",
"2006": "0"
},
{
"2013": "0",
"2014": "0",
"2015": "--"
}
]
}
推荐阅读
- html - 如何使用 sed 删除 HTML 中的注释?
- swift - Swift 错误“类型‘BookingDataModel’不符合协议‘Decodable’”
- react-native - 反应原生:无法将自定义高度设置为模态
- python - ModuleNotFoundError:在使用 Anaconda 的 Windows 10 上没有名为“dlib”的模块
- php - 如何使用仅使用 for 循环的 PHP 程序方法在数据库中插入数组值
- c++ - C++ uniform_real_distribution 每次都保持输出相同的值
- python - pip 安装项目而不复制整个项目文件夹
- c# - 将 JSON 从 OdooRPC 反序列化为 C# 对象
- cassandra - Datastax OpsCenter 用于从节点收集指标的默认一致性级别
- javascript - 带有 Lodash Debounce 的 VueJS 计算属性