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

mcg*_*298 11 python json string-formatting python-3.x

Python版本3.5

我正在尝试进行API调用以使用json作为格式配置设备.一些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)
Run Code Online (Sandbox Code Playgroud)

回溯(最近一次调用最后一次):文件"C:/ ...,第49行,在'''.format('a')KeyError:'\n"fvAp"'

工作EX:

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)
Run Code Online (Sandbox Code Playgroud)

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

sko*_*kin 16

格式字符串语法部分说:

格式字符串包含由大括号括起的"替换字段" {}.大括号中未包含的任何内容都被视为文本文本,它将不加改变地复制到输出中.如果你需要在文字文本中包含一个大括号字符,可以通过加倍来转义它:{{}}.

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

>>> '{{"fvAp": {{"attributes": {{"name": {}}}}}}}'.format('"app-name"')
'{"fvAp": {"attributes": {"name": "app-name"}}}'
Run Code Online (Sandbox Code Playgroud)

这看起来很糟糕.

有一个更好的方法来做到这一点string.Template:

>>> from string import Template
>>> t = Template('{"fvAp": {"attributes": {"name": "${name}"}}')
>>> t.substitute(name='StackOverflow')
'{"fvAp": {"attributes": {"name": "StackOverflow"}}'
Run Code Online (Sandbox Code Playgroud)

虽然我建议你放弃使用这种方式生成配置的想法并使用工厂功能,json.dumps而是:

>>> import json
>>> def make_config(name):
...     return {'fvAp': {'attributes': {'name': name}}}
>>> app_config = make_config('StackOverflow')
>>> json.dumps(app_config)
'{"fvAp": {"attributes": {"name": "StackOverflow"}}}'
Run Code Online (Sandbox Code Playgroud)