【问题标题】:How to use str.format inside a string of json format?如何在 json 格式的字符串中使用 str.format?
【发布时间】:2017-02-18 07:21:37
【问题描述】:

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)

回溯(最近一次调用最后一次):文件“C:/...,第 49 行,在 '''.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 方法使其工作?

【问题讨论】:

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


【解决方案1】:

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"}}}'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-27
    • 2015-11-09
    • 2021-07-28
    • 2019-11-11
    • 2023-03-11
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多