Module 08 · Lesson 03
JSON Files and Data
Save and load whole lists and dictionaries as JSON: convert with dumps and loads, read and write files with dump and load, format the output, and know which Python values change on the way.
- About 8 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Python data to JSON text
- Save and load a file
- Spot round-trip changes
- Watch data travel
Data as text
JSON writes lists and dictionaries as plain text, so any program, in any language, can read them back.
dumps
json.dumps(data)turns Python data into a JSON string.loads
json.loads(text)turns JSON text back into lists and dictionaries.dump and load
Without the s they work with files:
json.dump(data, f)andjson.load(f).Readable
indent=2spreads the text over lines.sort_keys=Truekeeps the key order stable.
JSON everywhere
JSON is how most programs on the internet pass data to each other.
- Web APIsWeather, maps and news services send their data as JSON.
- Game savesYour inventory and level can be saved as one JSON object.
- Settings filesMany apps keep their settings in a
.jsonfile. - PlaylistsA playlist exports as a list of song dictionaries.
Saving data as JSON
This line writes a dictionary to a file. Tap each part to see its job.
Part 1 of 6
module:The json module, loaded with import json.
Turn data into JSON and back
Pick an example, change it, then press Run. Say what you expect to see before you press. Each Run starts with no files, so every example writes its own.
Example 1 of 6dumps
dumps() turns Python data into JSON text. Watch what happens to True and None.
Your turn: Add a list of items to the dictionary and dump it again.
import json
player = {"name": "Ana", "level": 3, "online": True, "guild": None}
text = json.dumps(player)
print(text)
print(type(text).__name__)Press Run to see what it prints.Watch data travel as text
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- import json
- team = {"name": "Owls", "wins": 3}
- text = json.dumps(team)
- back = json.loads(text)
- back["wins"] += 1
- print(text)
- print(back)
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.None and True as JSON:
import json
print(json.dumps([None, True]))0 of 6 answered
Common JSON misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
import json text = json.dumps(data) # Python -> JSON string data = json.loads(text) # JSON string -> Python json.dump(data, f) # write to an open file data = json.load(f) # read from an open file json.dumps(data, indent=2, sort_keys=True) # readable and stable json.dumps(data, ensure_ascii=False) # keep accented letters
Press Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
Saving app settings between runs
Save a settings dictionary to a JSON file, load it back, change one value, save it again, and show the final file.
import json
from pathlib import Path
path = Path("settings.json")
settings = {"theme": "light", "volume": 7, "shortcuts": ["save", "undo"]}
path.write_text(json.dumps(settings, indent=2), encoding="utf-8")
loaded = json.loads(path.read_text(encoding="utf-8"))
loaded["theme"] = "dark"
loaded["shortcuts"].append("redo")
path.write_text(json.dumps(loaded, indent=2), encoding="utf-8")
print(path.read_text(encoding="utf-8"))Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Mixing up load and loads
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
import json
with open("d.json", encoding="utf-8") as f:
data = json.loads(f)Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Food delivery
An order queue saved between shifts
A small delivery kitchen keeps open orders in a JSON file so the evening shift can pick up exactly where the afternoon shift stopped.
Why Python fits
The list of order dictionaries survives the program stopping, because it lives in a file as JSON. The second part could be a completely separate program, or even one written in another language, and still read the same data.
Pythonimport json from pathlib import Path queue = Path("orders.json") orders = [ {"id": 101, "items": ["pizza", "cola"], "paid": True}, {"id": 102, "items": ["salad"], "paid": False}, ] queue.write_text(json.dumps(orders, indent=2), encoding="utf-8") # Evening shift waiting = json.loads(queue.read_text(encoding="utf-8")) unpaid = [o["id"] for o in waiting if not o["paid"]] items = sum(len(o["items"]) for o in waiting) print(len(waiting), "orders,", items, "items, unpaid:", unpaid)OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Is JSON the same as a Python dictionary?
Can JSON store comments?
How do I save a date or a set?
How big can a JSON file be?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 7 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.