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"..也是一个参考:

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({'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相关问答推荐

筛选JSON数组以使用Jolt仅保留具有最新日期/时间的条目

我可以使用JQ来缩小数组中的json对象的范围吗?

如何使用Aeson解码带有Unicode字符的JSON文件?

通过在织女星简化图上裁剪来显示文本

来自json的可分析的构建报告

如果主对象中已存在属性,则不应在Jolt中引用次对象

使用 map_values Select 包含空格的字符串未按预期工作

使用 TypeScript 接口时如何修复未定义错误?

将环境变量值从 yaml 传递到 json

将来自 Golang 的 JSON API 调用响应输出到 nextjs 前端

xidel:是否可以从 JSON 对象中检索特定的嵌套值?

如何通过 jolt 将一个对象中的键和值添加到数组中的每个对象中

golang递归json来构造?

ORA-01422: 精确提取返回的行数超过了与 json 对象组合的请求数

如何限制resolveJsonModule的范围?

SyntaxError:Object.parse(本机)AngularJS中的意外标记o

如何在返回对象的 Spring MVC @RestController @ResponseBody 类中响应 HTTP 状态代码?

Jsonpath 与 Jackson 或 Gson

JSON 模式 - 如果对象*不*包含特定属性则有效

Jersey 2.0 相当于 POJOMappingFeature