如何在json格式的字符串中使用str.format函数?
如何在json格式的字符串中使用str.format函数?
Python 版本3.5
我正在尝试使用json作为格式进行API调用以配置设备。根据所需的命名,一些json将有所不同,因此我需要在字符串中调用一个变量。我可以使用旧样式的%s... % (variable)
实现这一点,但不能使用新样式的{}... .format(variable)
。
失败的例子:
(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
方法使其工作?