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.
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]} | Python | JSON | Example in JSON |
|---|---|---|
| dict | object | {"battery": 87} |
| list | array | [1, 2, 3] |
| str | string | "Probe 7" (double quotes only) |
| int or float | number | 87 or 2.5 |
| True and False | true and false | lowercase |
| None | null | null |
| Text | Valid JSON? |
|---|---|
| {"crew": 4} | ? |
| {'crew': 4} | ? |
| [true, false, null] | ? |
| {"ready": True} | ? |
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]' | Statement | True 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. | ? |
JSON keeps the keys and the shape of your data. Tomorrow you will write JSON into a file.