我正在尝试使用 .format() 生成 JSON 字符串。 我尝试了以下方法:
TODO_JSON = '{"id": {0},"title": {1},"completed:" {2}}'
print(TODO_JSON.format(42, 'Some Task', False))
这会引发
File "path/to/file", line 2, in <module>
print(TODO_JSON.format(42, 'Some Task', False))
KeyError: '"id"'
为什么会出现这个错误?为什么“id”被解释为键而不是字符串的一部分?
最佳答案
如果您需要文字 {}
和 ,
,您可以使用{}
在 str.format
中具有特殊含义(占位符和变量名) >格式{{
和}}
:
TODO_JSON = '{{"id": {0},"title": {1},"completed:" {2}}}'
print(TODO_JSON.format(42, 'Some Task', False))
# {"id": 42,"title": Some Task,"completed:" False}
关于python - python3 中的 JSON 字符串和 .format(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44092715/