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

查看:33
本文介绍了字符串格式 JSON 字符串给出 KeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这段代码会给出一个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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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