为什么这段代码会给出一个KeyError
?
Why does this code give a 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"'
需要把外大括号加倍;否则 Python 认为 { "File"..
也是一个引用:
You need to double the outer braces; otherwise Python thinks { "File"..
is a reference too:
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
模块:
If, indicentally, you are producing JSON output, you'd be better off using the 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标准的要求.
Note the lowercase true
in the output, as required by the JSON standard.
这篇关于字符串格式 JSON 字符串给出 KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!