Syllabus Lesson 40 of 239 · Files, Errors & Modules
Files, Errors & Modules

Saving Data as JSON

JSON is the everyday format for structured data: settings files, API responses, saved app state. The beauty of it is that Python dicts and lists map directly onto JSON objects and arrays.

The json module gives you two pairs of functions. For strings:

  • json.dumps(obj) turns a Python object into a JSON string (dump-s for string).
  • json.loads(text) parses a JSON string back into Python.
import json

data = {"name": "Ada", "langs": ["py", "rs"], "active": True}
text = json.dumps(data)
print(text)

back = json.loads(text)
print(back["name"])

Going to and from a string like that is called a round-trip: json.loads(json.dumps(data)) == data. A few translations happen automatically: Python True becomes true, None becomes null, and dict keys always come back as strings.

For files there is also json.dump(obj, f) and json.load(f) (no s), which write to and read from an open file. Pass indent=2 to dumps/dump when you want it pretty-printed for humans.

Your turn

Start from the dict config = {"theme": "dark", "volume": 7, "tags": ["a", "b"]}. Convert it to a JSON string named config_json with json.dumps, then parse that string back into a dict named restored with json.loads. The round-trip should give you back an equal dict.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output