字符串格式 JSON 字符串给出 KeyError

2022-01-15 00:00:00 python string json format

问题描述

为什么这段代码会给出一个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.

相关文章