本文介绍了字符串格式JSON字符串给出KeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么这段代码给出一个 KeyError
? output_format =
{
File:{filename},
Success:{success},
ErrorMessage:{error_msg},
LogIdentifier:{log_identifier}
}
print output_format.format(filename ='My_file_name',
success =
error_msg ='',
log_identifier ='123')
错误讯息:
KeyError:'File'
解决方案
您需要将外括号加倍;否则Python认为 {File..
也是一个引用:
output_format ='{{File:{filename},Success:{success},ErrorMessage:{error_msg},LogIdentifier:{log_identifier}}}'
$ p $ >>>> print_format.format(filename ='My_file_name',
... success = True,
... error_msg ='',
... log_identifier ='123')
{File:My_file_name,Success:True,ErrorMessage:,LogIdentifier:123}
如果您显然是在生成JSON输出,那么最好使用: > import json
>>>打印json.dumps(Dict(File ='My_file_name',
... Success = True,
... ErrorMessage ='',
... LogIdentifier ='123'))
{LogIdentifier:123,ErrorMessage:,Success:true,File:My_file_name}
$ p $请注意输出中的小写 true
,正如JSON标准所要求的那样。 p>
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')
Error message:
KeyError: ' "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}" }}'
Result:
>>> print output_format.format(filename='My_file_name',
... success=True,
... error_msg='',
... log_identifier='123')
{ "File": "My_file_name", "Success": True, "ErrorMessage": "", "LogIdentifier": "123" }
If, indicentally, you are producing JSON output, you'd be better off using the json
module:
>>> import json
>>> print json.dumps(dict(File='My_file_name',
... Success=True,
... ErrorMessage='',
... LogIdentifier='123'))
{"LogIdentifier": "123", "ErrorMessage": "", "Success": true, "File": "My_file_name"}
Note the lowercase true
in the output, as required by the JSON standard.
这篇关于字符串格式JSON字符串给出KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!