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

Monday

Meet JSON
// Saving lists and dictionaries with JSON
⏱ about 30 min

Monday: Meet JSON

Rocket wants to save the whole crew list: names, roles and mission counts. He writes it to a text file, one value per line. Soon the file is full of numbers and words with no labels.

"Was that 4 a mission count or a station number?" he asks. "The file forgot which value was which."

Raven looks at the dictionaries in his program. "What do you notice?" she asks. "In Python, every value has a key next to it. The file lost the keys."

Nova displays a page of text with curly brackets, square brackets and labels. "Would you like a hint?" she asks. "There is a text format that looks almost exactly like Python lists and dictionaries. It is called JSON."

Rocket imports json in the shell to take a look.

What JSON looks like

JSON stands for JavaScript Object Notation, but almost every programming language can read and write it. It is plain text, so you can open a JSON file and read it yourself.

json.dumps() turns Python data into a JSON string. json.loads() turns a JSON string back into Python data. The s at the end stands for string.

>>> import json
>>> probe = {"name": "Probe 7", "battery": 87, "active": True, "zone": None}
>>> json.dumps(probe)
'{"name": "Probe 7", "battery": 87, "active": true, "zone": null}'
>>> json.loads('{"on": true, "n": [1, 2.5, null]}')
{'on': True, 'n': [1, 2.5, None]}
PythonJSONExample in JSON
dictobject{"battery": 87}
listarray[1, 2, 3]
strstring"Probe 7" (double quotes only)
int or floatnumber87 or 2.5
True and Falsetrue and falselowercase
Nonenullnull
TextValid JSON?
{"crew": 4}?
{'crew': 4}?
[true, false, null]?
{"ready": True}?
WHY THIS EXERCISEJSON looks like Python but has stricter rules: double quotes and lowercase true, false and null.
json.dumps(False) gives the JSON text:
json.dumps(None) gives the JSON text:
At your computer
1. In the IDLE shell, type import json and press Enter.
2. Type the probe dictionary exactly as shown and press Enter.
3. Type json.dumps(probe) and press Enter. Find true and null in the answer.
4. Type json.loads('[1, 2, 3]') and press Enter. Notice the single quotes around the JSON text.

Practice: data inside data

JSON can hold a list inside an object, or objects inside a list. After json.loads, you reach inside with one pair of square brackets per level.

>>> import json
>>> text = '{"crew": ["Rocket", "Raven"], "fuel": 90, "ready": false}'
>>> data = json.loads(text)
>>> data["crew"][1]
'Raven'
>>> data["ready"]
False
>>> json.dumps([1, "two", None])
'[1, "two", null]'
REACH INSIDE
  • Read the question.
  • Tap your answer.
Why does data["crew"][1] give Raven?
What does data["fuel"] give?
In the dumps answer, why does None become null?
What does data["crew"][0] give?
What does len(data["crew"]) give?
json.dumps(True) gives the JSON text:
StatementTrue or false?
JSON is plain text that people can read.?
A JSON array becomes a Python list.?
JSON allows single quotes around strings.?
json.loads reads JSON from a string.?
WHY THIS EXERCISEJSON is readable text with strict double quotes, and loads turns a JSON string into Python data.
Try it
1. In the shell, type the text and data lines exactly as shown.
2. Try data["crew"][-1] and data["fuel"] + 10.
3. Type json.dumps(data) and find false in the answer.

JSON keeps the keys and the shape of your data. Tomorrow you will write JSON into a file.