Skip to contentSkip to navigation

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) and json.load(f).

  • Readable

    indent=2 spreads the text over lines. sort_keys=True keeps 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 .json file.
  • 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

Tap any part of the code below, or press Next.1 of 6 explored

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.

Python
import json
player = {"name": "Ana", "level": 3, "online": True, "guild": None}
text = json.dumps(player)
print(text)
print(type(text).__name__)
Output
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.

  1. import json
  2. team = {"name": "Owls", "wins": 3}
  3. text = json.dumps(team)
  4. back = json.loads(text)
  5. back["wins"] += 1
  6. print(text)
  7. 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 notesOpen

What JSON is

JSON (JavaScript Object Notation) is a text format for structured data. It looks very like Python dictionaries and lists:

{"name": "Ana", "age": 31, "languages": ["Python", "SQL"], "admin": false, "manager": null}

Because it is plain text, any language can read and write it, which is why programs written in different languages use it to talk to each other. JSON has only a few kinds of value, and each matches a Python type:

JSON Python
object {...} dict
array [...] list
string "..." str
number 3, 2.5 int, float
true / false True / False
null None

Notice the small differences: JSON writes true, false and null in lower case, and it only allows double quotes around strings.

dumps and loads: text in memory

json.dumps() (dump to a string) turns Python data into JSON text. json.loads() (load from a string) turns JSON text back into Python data.

Try it 1: edit me, then Run
import json

user = {"name": "Ana", "age": 31, "admin": False, "manager": None}
text = json.dumps(user)
print(text)          # {"name": "Ana", "age": 31, "admin": false, "manager": null}
print(type(text))    # <class 'str'>

back = json.loads(text)
print(back["age"] + 1)   # 32
Output
Press Run to see what it prints.

The result of dumps is just a string; you could print it, save it or send it over the network. The result of loads is ordinary Python data, so you use it with the same indexing and methods as any dictionary.

dump and load: files

Without the s, the functions work with an open file instead of a string:

Try it 2: edit me, then Run
with open("user.json", "w", encoding="utf-8") as f:
    json.dump(user, f)

with open("user.json", encoding="utf-8") as f:
    loaded = json.load(f)
Output
Press Run to see what it prints.

A handy memory aid: the s versions are for strings, the plain versions are for files. Mixing them up, such as passing a file to loads, is a very common mistake. With pathlib you can also write path.write_text(json.dumps(data), encoding="utf-8") and json.loads(path.read_text(encoding="utf-8")).

Readable output

By default dumps puts everything on one line. indent spreads it over several lines, and sort_keys orders the keys alphabetically, which makes files easier to read and to compare between versions:

Try it 3: edit me, then Run
settings = {"theme": "dark", "font": {"size": 14, "family": "Mono"}}
print(json.dumps(settings, indent=2, sort_keys=True))
Output
Press Run to see what it prints.
{
  "font": {
    "family": "Mono",
    "size": 14
  },
  "theme": "dark"
}

Text with accents or other non-English characters is escaped by default, so "café" is written as "caf\u00e9". That is still valid JSON and loads back correctly. Pass ensure_ascii=False if you want the real characters in the file, and then keep using encoding="utf-8".

What changes on a round trip

JSON has fewer types than Python, so some values come back different from how they went in:

  • A tuple becomes a JSON array, and comes back as a list.
  • Dictionary keys must be strings in JSON. Number keys are turned into strings: {1: "a"} comes back as {"1": "a"}.
  • Sets, dates and your own objects cannot be converted at all; dumps raises TypeError: Object of type set is not JSON serializable. Convert them first, for example a set to a sorted list.
Try it 4: edit me, then Run
data = {"point": (3, 4), 7: "lucky"}
print(json.loads(json.dumps(data)))   # {'point': [3, 4], '7': 'lucky'}
Output
Press Run to see what it prints.

If your program reads back its own data, plan for these changes: look up data["7"], not data[7].

Working with loaded data

Data loaded from JSON is often nested several levels deep. Reach into it step by step, just as with any nested dictionary and list:

Try it 5: edit me, then Run
reply = json.loads('{"city": "Oslo", "days": [{"temp": 4}, {"temp": 7}]}')
print(reply["days"][1]["temp"])            # 7
print(reply.get("country", "unknown"))     # unknown
Output
Press Run to see what it prints.

When a key might be missing, as is common with data from other systems, get with a default avoids a KeyError.

Broken JSON

json.loads is strict. Single quotes, a trailing comma, or Python's True and None all raise json.JSONDecodeError, along with the line and column of the first problem. That is a feature: a half-broken file is reported straight away instead of silently giving wrong data. Later lessons show how to catch the error and tell the user what went wrong.

Why not just use str()?

Printing a dictionary or calling str() on it gives Python's own notation, with single quotes and True and None. That text is not valid JSON, and other programs cannot read it reliably. Always use the json module when the data needs to be read back or shared.

Syntax

The general shape of the statements in this lesson.

syntax.py
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
Output
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

Beginner

Save a settings dictionary to a JSON file, load it back, change one value, save it again, and show the final file.

Python
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"))
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The settings go through JSON text into the file and come back as a normal dictionary, list included. After changing the copy in memory, the whole dictionary is written again; JSON files are usually replaced as a whole rather than edited in place.

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.

Buggy code: run it
import json
with open("d.json", encoding="utf-8") as f:
    data = json.loads(f)
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper

Write this instead

import json
with open("d.json", encoding="utf-8") as f:
    data = json.load(f)

Why it happens

loads expects a string of JSON text, but it was given the file object.

In the real world

Where this shows up in software people use every day.

  1. An order queue saved between shifts

    Food delivery

    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.

    Python
    import 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)
    Output
    Press 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?

They look alike, but JSON is text with stricter rules: double quotes only, lower-case true, false and null, and string keys. A dictionary is a live Python object.

Can JSON store comments?

No, standard JSON has no comments. If a settings file needs notes, add a field such as "_note" or keep the documentation elsewhere.

How do I save a date or a set?

Convert it to something JSON knows first: a date to an ISO string such as "2024-06-01", and a set to a sorted list. When you load the data, convert it back yourself. Keeping the conversion in two small functions, one for saving and one for loading, stops the rules from drifting apart.

How big can a JSON file be?

json.load reads the whole file into memory, so it suits files up to many megabytes. For huge datasets, formats such as CSV that can be read line by line, or a database, are better.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

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.

Create ID to save
Lessons done in this module0/4 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

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.