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

Python 如何在json格式的字符串中使用str.format?,python,json,python-3.x,string-formatting,Python,Json,Python 3.x,String Formatting,Python版本3.5 我正在尝试进行API调用,以使用json作为格式配置设备。一些json将根据所需的命名而变化,因此我需要在字符串中调用一个变量。我可以使用老式的%s(变量),但不使用新样式{}。格式(变量) 失败的EX: (Testing with {"fvAp":{"attributes":{"name":(variable)}}}) a = "\"app-name\"" app_config = ''' { "fvAp": { "attributes": { "name": {}

Python版本3.5

我正在尝试进行API调用,以使用json作为格式配置设备。一些json将根据所需的命名而变化,因此我需要在字符串中调用一个变量。我可以使用老式的
%s(变量)
,但不使用新样式
{}。格式(变量)

失败的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)
回溯(最近一次调用):文件“C:/…,第49行,格式为“”。格式('a')键错误:'\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
方法,则需要转义模板字符串中的所有JSON花括号:

>>> '{{"fvAp": {{"attributes": {{"name": {}}}}}}}'.format('"app-name"')
'{"fvAp": {"attributes": {"name": "app-name"}}}'
那看起来真糟糕

有一种更好的方法:

尽管我建议完全放弃以这种方式生成配置的想法,而是使用工厂函数:

可能重复的
>>> from string import Template
>>> t = Template('{"fvAp": {"attributes": {"name": "${name}"}}')
>>> t.substitute(name='StackOverflow')
'{"fvAp": {"attributes": {"name": "StackOverflow"}}'
>>> import json
>>> def make_config(name):
...     return {'fvAp': {'attributes': {'name': name}}}
>>> app_config = make_config('StackOverflow')
>>> json.dumps(app_config)
'{"fvAp": {"attributes": {"name": "StackOverflow"}}}'