为什么这段代码会给出一个KeyError
output_format = """
{
"File": "{filename}",
"Success": {success},
"ErrorMessage": "{error_msg}",
"LogIdentifier": "{log_identifier}"
}
"""
print output_format.format(filename='My_file_name',
success=True,
error_msg='',
log_identifier='123')
错误消息:
KeyError: ' "File"'
发布于 2013-05-03 10:31:26
你需要双倍的大括号;否则Python会认为{ "File"..
也是一个引用:
output_format = '{{ "File": "{filename}", "Success": {success}, "ErrorMessage": "{error_msg}", "LogIdentifier": "{log_identifier}" }}'
结果:
>>> print output_format.format(filename='My_file_name',
... success=True,
... error_msg='',
... log_identifier='123')
{ "File": "My_file_name", "Success": True, "ErrorMessage": "", "LogIdentifier": "123" }
如果您正在生成JSON输出,那么最好使用json
module
>>> import json
>>> print json.dumps({'File': 'My_file_name',
... 'Success': True,
... 'ErrorMessage': '',
... 'LogIdentifier': '123'})
{"LogIdentifier": "123", "ErrorMessage": "", "Success": true, "File": "My_file_name"}
请注意输出中的小写true
,这是JSON标准所要求的。
发布于 2020-10-20 17:43:52
正如都铎在给另一个答案的comment中提到的那样,Template类是最适合我的解决方案。我正在处理嵌套的字典或字典列表,但处理这些字典并不简单。
使用模板虽然解决方案非常简单。
我从一个转换为字符串的字典开始。然后,我将所有{
实例替换为${
,它是用来替换占位符的模板标识符。
实现这一点的关键点是使用模板方法safe_substitute
。它将替换所有有效的占位符,如${user_id}
,但忽略字典结构中的任何无效占位符,如${'name': 'John', ...
。
替换完成后,我删除了所有剩余的$
,并将字符串转换回字典。
在下面的代码中,resolve_placeholders
返回一个字典,其中每个键都与有效负载字符串中的一个占位符匹配,并且值被模板类替换。
from string import Template
.
.
.
payload = json.dumps(payload)
payload = payload.replace('{', '${')
replace_values = self.resolve_placeholders(payload)
if replace_values:
string_template = Template(payload)
payload = string_template.safe_substitute(replace_values)
payload = payload.replace('${', '{')
payload = json.loads(payload)
https://stackoverflow.com/questions/16356810
复制相似问题