python - 使用 Python 将格式化的 JSON 写入文件
问题描述
我想使用 shell 脚本将格式化(即缩进)JSON 配置文件写入远程计算机。
我的代码:
json_config = {
"api-listen": true,
"api-network": true,
"multi-version": "1",
"pools": [
{
"pass": "123",
"url": "antpool.com:3333"
},
{
"pass": "123",
"url": "antpool.com:443"
},
{
"pass": "123",
"antpool.com:25"
}
]
}
# format the new configuration
json_config_formatted = json.dumps(json.dumps(json_config), indent=4)
# write the new config
connection.sendShell('echo "{}" | cat > "/config/bmminer.conf"'.format(json_config_formatted))
但是,所有内容都写在一行上。如何保留字符串的格式?
解决方案
首先,您调用 json.dumps 两次,因此您正在创建一个本身包含 JSON 的 JSON 字符串。
其次,您应该使用 Python 而不是 shell 编写文件。
json_config = {
...
}
# format the new configuration
with open("/config/bmminer.conf", "w") as conf:
json.dump(json_config, conf, indent=4)
对于远程计算机,如何正确获取数据取决于您的库。我不知道是什么sendShell
。
推荐阅读
- objective-c - 为什么 RunLoop 不会阻止整个线程执行?
- c# - Azure 服务总线主题 - 订阅消息到期
- angular - 使用从 API 服务器检索的服务在组件之间共享数据
- reactjs - React tabs - 切换破坏组件,需要维护相同的组件
- python - 类似于 Pandas 中的 Pivot
- wordpress - WordPress 多站点图像和文件不起作用
- java - 通过比较器与 java 流 api 对地图的值进行排序
- java - Ninja 框架预检
- r - 我怎么知道强制引入了哪些 NA?
- reporting-services - 根据参数值更改使用的 SSRS 表达式