← Back to course
Code Crew G6+ / Week 09 / Crew Quest
6/6
Week 09 Β· Structured data

Crew Quest

Crew Quest: Design a data file
// Saving lists and dictionaries with JSON
⏱ about 30 min

Saturday: Crew Quest: Design a data file

Before any code is written for a big project, someone has to decide what the data looks like. Today the crew is designing the data file for a mission plan.

"A list of steps," Rocket says. "Each step has a name, how many minutes it takes, and whether it is done."

Raven writes it out on the whiteboard in JSON, with careful double quotes. "What do you notice?" she asks. "Writing it by hand first shows us the shape before Python sees it."

Nova checks each bracket and quote mark, glowing green at each one. "I found a pattern," she says. "If json.loads accepts your text, your design is valid JSON."

Rocket copies the design into the shell to test it.

  1. JSON is text that looks like Python lists and dictionaries, with double quotes and lowercase true, false and null.
  2. json.dump(data, f, indent=2) writes data to a file opened with "w".
  3. json.load(f) reads it back as Python lists and dictionaries.
  4. Read, change, write back: load, update the Python data, dump it again.
  5. os.path.exists(name) checks for a file, so the first run can start fresh.
{
  "mission": "Weekend launch",
  "steps": [
    {"name": "Check fuel", "minutes": 10, "done": true},
    {"name": "Check weather", "minutes": 5, "done": false}
  ]
}
In the plan above, how many steps are there?
After json.load, what Python value does "done": false become?
β—‡ DESIGN YOUR OWN DATA FILE
With a grown-up, choose something to keep track of, like books read, plants watered or chores done. Keep it about things, not people.
Design one JSON object for it on paper. Decide the keys and an example value for each.
Type it into the shell inside json.loads('...') to check it is valid JSON.
MORE REVIEW: WEEK 9
  • Read the question.
  • Tap your answer.
What does json.dumps([True, None]) give?
Which mode should json.dump write with?
What are the three steps for updating saved data?

Wonderful work. Next week you will become a bug detective: reading tracebacks, catching errors and writing tests.

← Friday