Lesson 8 of 10

Reading and writing JSON

Goal

From text to data and back

01

Explanation

JSON is how programs exchange data. You'll find it in API responses, in config files and in whatever travels between the server and the browser. What reaches you is ultimately text, not a dict, so you can't read a key from it until you convert it.

json.loads(text) turns the text into Python dicts and lists, and json.dumps(data) turns them back into text. The indent=2 argument spreads that text over several lines with clear indentation so it's easy to read. As long as your data is dicts, lists, strings and numbers, nothing is lost when you turn it into text and back.

The trap: by default dumps turns every non-ASCII character into an escape code, so "café" becomes "caf\u00e9". That's technically correct, but it's hard for people to read, and it makes the text longer. ensure_ascii=False keeps the characters as they are.

02

Your task

Convert raw into order with json.loads, and add the key "total" holding the sum of price * qty for every entry in items. Then build pretty with json.dumps so the accented characters stay readable and the indent is 2.

Checks

5 checks
  1. order is a dict, not a string
  2. total is the sum of price times quantity
  3. pretty loads back into the same order
  4. Accented text in pretty is readable
  5. pretty is indented by two spaces
main.py
OutputPython (Pyodide)

Loading Python. This only happens once. Your browser keeps it after that.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.