JSON in files
Python · Unit 17: Files
- Full plan
- Python
- 10 exercises
A CSV only holds a flat table of text. JSON is a text format that stores whole lists and dictionaries, with their numbers and their text.
json.dump(data, f) writes the data into the open file.
import json
data = {"grape": 3, "bread": 2}
with open("a.json", "w") as f:
json.dump(data, f)
print(open("a.json").read())Prints
{"grape": 3, "bread": 2}The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Complete the code
Complete it to save the list in the file.
3. Predict the output
What does this code print?
4. Complete the code
Complete it to get the data back out of the file.
5. Predict the output
What does this code print?
6. Multiple choice
You want to save a dictionary that has a list inside it. Which format suits you?
7. Find the bug
This program should show Ana's mark. Which line has the bug?
8. Put the lines in order
Put the lines in order to save the dictionary and read it back.
9. Find the case that fails
parse(text)savestextin a file and should return the data it holds, or{}if the text isn't valid JSON. Which call breaks it?10. Predict the output
What does this code print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.