简体   繁体   中英

Python multi-line JSON and variables

I'm trying to encode a somewhat large JSON in Python (v2.7) and I'm having trouble putting in my variables!

As the JSON is multi-line and to keep my code neat I've decided to use the triple double quotation mark to make it look as follows:

my_json = """{
        "settings": {
                "serial": "1",
                "status": "2",
                "ersion": "3"
        },
        "config": {
                "active": "4",
                "version": "5"
        }
}"""

To encode this, and output it works well for me, but I'm not sure how I can change the numbers I have there and replace them by variable strings. I've tried:

    "settings": {
            "serial": 'json_serial',

but to no avail. Any help would be appreciated!

Why don't you make it a dictionary and set variables then use the json library to make it into json

import json
json_serial = "123"
my_json = {
    'settings': {
        "serial": json_serial,
        "status": '2',
        "ersion": '3',
    },
    'config': {
        'active': '4',
        'version': '5'
    }
}
print(json.dumps(my_json))

If you absolutely insist on generating JSON with string concatenation -- and, to be clear, you absolutely shouldn't -- the only way to be entirely certain that your output is valid JSON is to generate the substrings being substituted with a JSON generator. That is:

'''"settings" : {
  "serial"   : {serial},
  "version"  : {version}
}'''.format(serial=json.dumps("5"), version=json.dumps(1))

But don't. Really, really don't. The answer by @davidejones is the Right Thing for this scenario.

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