本文介紹了字符串格式 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!