如何在json格式的字符串

时间:2016-10-09 21:19:43

标签: python json python-3.x string-formatting

Python Version 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)
  

回溯(最近一次呼叫最后一次):文件" C:/ ...,第49行,''。' 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)

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

1 个答案:

答案 0 :(得分:9)

Format String Syntax部分说:

  

格式字符串包含由大括号{}包围的“替换字段”。大括号中未包含的任何内容都被视为文本文本,它将不加改变地复制到输出中。如果您需要在文字文本中包含大括号字符,则可以通过加倍来对其进行转义:{{}}

因此,如果您想使用.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='StackOverflow')
'{"fvAp": {"attributes": {"name": "StackOverflow"}}'

虽然我建议你放弃使用这种方式生成配置的想法并使用工厂函数而不是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"}}}'