简体   繁体   中英

Write formatted JSON to file using Python

I would like to write a formatted (ie indented) JSON configuration file to a remote computer using a shell script.

My code:

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))

However, everything gets written on a single line. How can I preserve the formatting of the string?

First, you are calling json.dumps twice, so you are making a single JSON string which itself contains JSON.

Second, you should write the file with Python, not a shell.

json_config = {
    ...
}

# format the new configuration
with open("/config/bmminer.conf", "w") as conf:
    json.dump(json_config, conf, indent=4)

For a remote computer, how you get the data there correctly depends on your library. I don't know what sendShell is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM