Paul's Python CoursePPC

JSON and the json module

Not met yet

JSON is text that looks like Python's dictionaries and lists, and nearly every web API speaks it. json.dumps(value) turns a value into JSON text and json.loads(text) turns it back; json.dump(value, file) and json.load(file) do the same with an open file. The round trip isn't perfect: tuples come back as lists, dictionary keys always come back as text, and True and None are written true and null.

Try it

main.py
import json

booking = {"room": "Studio", "desk": 2, "paid": True, "notes": None}
text = json.dumps(booking)
print(text)
print(json.loads(text) == booking)

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks a tuple saved as JSON comes back as a tuple. JSON has only lists, so it comes back as a list.
  • Thinks whole-number dictionary keys survive a JSON round trip. JSON keys are always text.
  • Thinks a file's write() can write a list or a dictionary. It takes text; json.dump turns the value into text first.

Where it comes up