简体   繁体   English

Python多行JSON和变量

[英]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! 我正在尝试在Python(v2.7)中编码一个有点大的JSON,我在输入变量时遇到了麻烦!

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: 由于JSON是多行的并且为了保持我的代码整洁,我决定使用三重双引号使其看起来如下:

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 为什么不把它变成字典并设置变量然后使用json库将它变成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. 如果你绝对坚持使用字符串连接生成JSON - 并且,为了清楚,你绝对不应该 - 唯一的方法是完全确定你的输出是有效的JSON是生成用JSON生成器替换的子串。 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. @davidejones的答案是这种情况的正确方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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