×

python · level 2 · unit 5 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

turns your data into text, and json turns it back.

Programs share data as text, and the favourite format is JSON. It looks almost like Python: curly brackets, square brackets, colons and commas. A weather app, a game and a website can all read it.

json.dumps(data) turns dictionaries and lists into a JSON string. json.loads(text) does the opposite: it parses JSON text back into dictionaries and lists. Remember the s: dump string, load string.

JSON uses double quotes only, and writes true, false and null where Python writes True, False and None. Wrap JSON text in single quotes in your code, so its double quotes do not end the string.

import json
pet = {"name": "Rex", "age": 3, "vaccinated": True, "chip": None}
text = json.dumps(pet)
print(text)
back = json.loads(text)
print(back["name"], back["vaccinated"])

json.dumps(pet, indent=2) spreads the JSON over several lines, one pair per line.