首页 > 解决方案 > 使用 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))

但是,所有内容都写在一行上。如何保留字符串的格式?

标签: pythonshell

解决方案


首先,您调用 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


推荐阅读