2

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 ?

2
  • 3
    This is fine for learning, but I'd use the json module for practical work as it'll escape things for you. Commented May 21, 2017 at 3:05
  • @NickT I was looking for a good reason to use the json module instead of a simple string – you provide a good one. Commented May 21, 2017 at 3:23

3 Answers 3

6

{} 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}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer.
1

You can use % formatting style.

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

Comments

0

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)

1 Comment

My data comes in as a tuple from the database, so it's quire simple to just pass it in the string. What is the benefit of creating a dict and parsing it ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.