Theo
Theo

Reputation: 1270

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 ?

Upvotes: 2

Views: 4385

Answers (3)

Taku
Taku

Reputation: 33704

You can use % formatting style.

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

Upvotes: 1

Francois Mockers
Francois Mockers

Reputation: 733

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)

Upvotes: 0

akuiper
akuiper

Reputation: 214927

{} 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}

Upvotes: 6

Related Questions