json.dumps() and json.loads()

Turn data into JSON text to save or send it, and back into Python data.

Syntax

import json
text = json.dumps(data)
data = json.loads(text)
  • JSON keys are always text, and tuples come back as lists.

Example

import json
text = json.dumps({"hp": 20})
print(text)
print(json.loads(text)["hp"])

Output:

{"hp": 20}
20

Common mistakes

  • dumps and loads work with strings; dump and load work with files.

Practise it