JSON
🌍 In real life. When a phone app saves your settings, or a website sends your profile to your phone, the data travels as plain text in an agreed format, so any program in any language can read it. The most common of those formats is JSON, and it looks almost exactly like Python's dictionaries and lists.
The idea in one sentence: json.dump/json.dumps turn Python dictionaries and lists into JSON text, and json.load/json.loads turn JSON text back into Python data.
Its words:
- JSON: a text format for data: objects
{}, arrays[], strings in double quotes, numbers,true,false,null json.dumps(data)/json.loads(text): to and from a stringjson.dump(data, f)/json.load(f): to and from a fileindent=2: spreads the JSON over lines, easy for people to read
Step by step, for json.loads('{"theme": "dark"}'):
- Python reads the JSON object
{...}and makes a dictionary. "theme"becomes a Python string key, and"dark"its value.- The result is
{'theme': 'dark'}, ready to use like any dictionary.
import json
pet = {"name": "Rex", "age": 3, "vaccinated": True, "owner": None}
text = json.dumps(pet)
print(text)
back = json.loads(text)
print(back["name"], back["vaccinated"])json.load(f) reads JSON straight from a file, and json.dump(data, f) writes it. What comes out is ordinary Python data, so you use it like any dictionary:
import json
with open("settings.json") as f:
settings = json.load(f)
print(settings["theme"])
print(settings.get("font", "big"))To change a JSON file: load it, change the data, then dump it back. indent=2 makes the file easy for people to read.
import json
with open("settings.json") as f:
settings = json.load(f)
settings["volume"] = 9
with open("settings.json", "w") as f:
json.dump(settings, f, indent=2)
with open("settings.json") as f:
print(f.read())Why JSON? Your program's dictionary lives only in memory and vanishes when the program ends. Saving it as JSON keeps it in a file for next time, in a format that a web page, a phone app or a program in another language can read too.
Mistakes and edge cases.
- Single quotes in JSON text.
json.loads("{'a': 1}")givesjson.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1). JSON strings use double quotes. - Data JSON can't hold.
json.dumps({1, 2})givesTypeError: Object of type set is not JSON serializable. Turn a set into a list first. - Number keys come back as strings.
{1: "a"}saved and loaded again is{'1': 'a'}: JSON keys are always strings. - Tuples come back as lists.
(1, 2)is saved as[1, 2].
Quiz
What does this print?
import json print(json.dumps({"ok": True, "items": [1, 2]}))What does this print?
import json data = json.loads('{"a": null, "b": false}') print(data)Which is valid JSON?
- {"name": "Bo"}
- {'name': 'Bo'}
- {"name": "Bo",}
What does this print?
import json with open("d.json", "w") as f: json.dump({"x": 1}, f) with open("d.json") as f: print(json.load(f)["x"] + 1)Which line has a mistake?
import json text = "{'theme': 'dark'}" settings = json.loads(text) print(settings["theme"])
Coding tasks
Write
get_theme(filename)that loads the JSON file and returns its"theme".Write
to_json(data)that returns data as JSON text.scores.jsonmaps names to scores. Writeadd_point(filename, name)that adds 1 to that name's score and saves the file again (with plainjson.dump, no indent).