如何在 json 格式的字符串中使用 str.format?

How to use str.format inside a string of json format?

Python 版本 3.5

我正在尝试使用 json 作为格式进行 API 调用以配置设备。有些 json 会根据所需的命名而有所不同,因此我需要在字符串中调用一个变量。我可以使用旧样式 %s... % (variable) 完成此操作,但不能使用新样式 {}... .format(variable).

失败的 EX:

(Testing with {"fvAp":{"attributes":{"name":(variable)}}})

a = "\"app-name\""

app_config = ''' { "fvAp": { "attributes": { "name": {} }, "children": [ { "fvAEPg": { "attributes": { "name": "app" }, "children": [ { "fvRsBd": { "attributes": { "tnFvBDName": "default" }, } } ] } }, { "fvAEPg": { "attributes": { "name": "db" }, "children": [ { "fvRsBd": { "attributes": { "tnFvBDName": "default" }, } } ] } } ] } } '''.format(a)

print(app_config)

Traceback (most recent call last): File "C:/..., line 49, in '''.format('a') KeyError: '\n "fvAp"'

工作前任:

a = "\"app-name\""

app_config = ''' { "fvAp": { "attributes": { "name": %s }, "children": [ { "fvAEPg": { "attributes": { "name": "app" }, "children": [ { "fvRsBd": { "attributes": { "tnFvBDName": "default" }, } } ] } }, { "fvAEPg": { "attributes": { "name": "db" }, "children": [ { "fvRsBd": { "attributes": { "tnFvBDName": "default" }, } } ] } } ] } } ''' % a

print(app_config)

如何使用 str.format 方法让它工作?

Format String Syntax 部分说:

Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

所以如果你想使用 .format 方法,你需要转义模板字符串中的所有 JSON 花括号:

>>> '{{"fvAp": {{"attributes": {{"name": {}}}}}}}'.format('"app-name"')
'{"fvAp": {"attributes": {"name": "app-name"}}}'

看起来真糟糕。

有更好的方法 string.Template:

>>> from string import Template
>>> t = Template('{"fvAp": {"attributes": {"name": "${name}"}}')
>>> t.substitute(name='Whosebug')
'{"fvAp": {"attributes": {"name": "Whosebug"}}'

尽管我建议完全放弃以这种方式生成配置并使用工厂函数和 json.dumps 的想法:

>>> import json
>>> def make_config(name):
...     return {'fvAp': {'attributes': {'name': name}}}
>>> app_config = make_config('Whosebug')
>>> json.dumps(app_config)
'{"fvAp": {"attributes": {"name": "Whosebug"}}}'