简体   繁体   中英

JSON string and .format() in python3

I'm trying to generate a JSON string using .format(). I tried the following:

TODO_JSON = '{"id": {0},"title": {1},"completed:" {2}}'
print(TODO_JSON.format(42, 'Some Task', False))

which raises

File "path/to/file", line 2, in <module>
    print(TODO_JSON.format(42, 'Some Task', False))
KeyError: '"id"'

Why is this error occurring ? Why is 'id' getting interpreted as a key and not as part of a string ?

{} has special meaning in str.format (place holder and variable name), if you need literal {} with format , you can use {{ and }} :

TODO_JSON = '{{"id": {0},"title": {1},"completed:" {2}}}'
print(TODO_JSON.format(42, 'Some Task', False))
# {"id": 42,"title": Some Task,"completed:" False}

You can use % formatting style.

TODO_JSON = '{"id": %i,"title": %s,"completed:" %s}'
print(TODO_JSON % (42, 'Some Task', False))

Because it's trying to parse to outer {} that are part of the json formatting as something that should be formatted by format

But you should try the json module

import json
todo = {'id': 42, 'title': 'Some Task', 'completed': False}
TODO_JSON = json.dumps(todo)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM