Now that Rocket has seen JSON, he wants the crew list saved in a file, with every key and value kept. He remembers how much work the weather log took, splitting every line by commas.
"Do I have to write every bracket and quote mark myself?" he asks, worried.
Raven shakes her head and smiles. "What do you notice about the shell yesterday?" she asks. "json.dumps did all the brackets for us. Maybe there is a version that writes to a file."
Nova shows a file icon filling neatly with indented lines. "I found a pattern," she says. "dumps makes a string. dump, without the s, writes straight into a file. Add indent to make it easy to read."
Rocket types json.dump and saves the whole crew in one line.
json.dump(data, f) writes your data into an open file as JSON. Open the file with "w", because the new JSON should replace the old file, not be added to the end.
indent=2 puts each item on its own line, indented two spaces per level. Without it, everything goes on one long line. Both work, but people prefer reading the indented version.
# save_crew.py
import json
crew = [
{"name": "Rocket", "role": "engineer", "missions": 3},
{"name": "Raven", "role": "explorer", "missions": 4},
]
with open("crew.json", "w") as f:
json.dump(crew, f, indent=2)
print("Saved", len(crew), "crew records") The shell shows Saved 2 crew records. This is what crew.json holds:
[
{
"name": "Rocket",
"role": "engineer",
"missions": 3
},
{
"name": "Raven",
"role": "explorer",
"missions": 4
}
] Many apps save their settings as a JSON object. Here a dictionary of settings is written to settings.json.
# save_settings.py
import json
settings = {"sound": True, "volume": 7, "theme": "night"}
with open("settings.json", "w") as f:
json.dump(settings, f, indent=2)
print("Saved", len(settings), "settings") {
"sound": true,
"volume": 7,
"theme": "night"
} | Statement | True or false? |
|---|---|
| json.dump writes into an open file. | ? |
| json.dumps writes into an open file. | ? |
| A file for json.dump should usually be opened with "w". | ? |
| indent changes the values saved in the file. | ? |
One line saved a whole list of dictionaries. Tomorrow you will load it back.