字符串格式 JSON 字符串给出 KeyError [英] String format a JSON string gives KeyError

查看:5

问题描述

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆