🗂️
Coding🎓 Ages 14-18Intermediate 11 min read

Working with JSON in Python: Save and Load Data

Learn to read and write JSON in Python with the json module: json.dumps, json.loads, json.dump and json.load, plus a worked example saving a high-score file.

Key takeaways

  • JSON is a text format for storing structured data that almost every language understands
  • json.dumps turns a Python object into a JSON string; json.loads turns a JSON string back into Python
  • json.dump and json.load do the same thing but write to and read from files
  • Python dicts and lists map cleanly onto JSON objects and arrays

What is JSON?

JSON (JavaScript Object Notation) is a simple text format for storing structured data. It looks almost identical to Python dictionaries and lists, which makes it a natural fit for Python programs. Web APIs, configuration files and game save files all use JSON because nearly every programming language can read it.

Here is a small piece of JSON:

{
  "name": "Ada",
  "level": 7,
  "skills": ["python", "math"],
  "active": true
}

Notice the curly braces for an object, square brackets for a list, double quotes around every key, and true in lowercase. These are JSON's rules. The good news: Python's built-in json module translates between this text and real Python objects for you.

This lesson builds on reading and writing files in Python and on dictionaries in Python, so review those if either is unfamiliar.

The four functions you need

The json module gives four core functions. The trick to remembering them is the letter s, which stands for string:

FunctionDirectionWorks with
json.dumpsPython → JSONa string
json.loadsJSON → Pythona string
json.dumpPython → JSONa file
json.loadJSON → Pythona file

"dump" means writing data out; "load" means reading it in. The s versions handle strings in memory; the plain versions handle files.

Python to JSON string and back

import json

player = {
    "name": "Ada",
    "level": 7,
    "skills": ["python", "math"],
    "active": True
}

text = json.dumps(player)
print(text)
# {"name": "Ada", "level": 7, "skills": ["python", "math"], "active": true}

back = json.loads(text)
print(back["name"])     # Ada
print(back["level"])    # 7

Line by line:

  • import json loads the module. Always do this first.
  • json.dumps(player) converts the dictionary into a JSON string. Notice Python's True became JSON's true automatically.
  • json.loads(text) reverses the process, giving back a normal Python dictionary you can index with back["name"].

Pretty printing

A long JSON string on one line is hard to read. The indent option spreads it over multiple lines:

import json

data = {"name": "Ada", "skills": ["python", "math"]}
print(json.dumps(data, indent=2))

Output:

{
  "name": "Ada",
  "skills": [
    "python",
    "math"
  ]
}

indent=2 tells Python to use two spaces per level of nesting. This is great for save files you might open and read by hand.

Worked example: a high-score file

Let's save a list of high scores to disk and load it back next time the game runs.

import json

scores = [
    {"name": "Ada", "points": 120},
    {"name": "Bel", "points": 95},
    {"name": "Cy",  "points": 88}
]

# Write the scores to a file
with open("scores.json", "w") as f:
    json.dump(scores, f, indent=2)

print("Scores saved.")

Walk through it:

  • We build a list of dictionaries — exactly the kind of structured data JSON handles well.
  • open("scores.json", "w") opens a file for writing. The with block closes it automatically.
  • json.dump(scores, f, indent=2) writes the JSON straight into the file f. Note: no s because we are writing to a file, not making a string.

Now read it back in a separate run:

import json

with open("scores.json", "r") as f:
    loaded = json.load(f)

for entry in loaded:
    print(entry["name"], "scored", entry["points"])

Output:

Ada scored 120
Bel scored 95
Cy scored 88

json.load(f) reads the file and rebuilds the original list of dictionaries. Because the data structure is preserved exactly, your loop works just as if you had typed the list yourself.

Adding a new score

A common task is loading existing data, changing it, and saving again:

import json

with open("scores.json", "r") as f:
    scores = json.load(f)

scores.append({"name": "Dot", "points": 110})

with open("scores.json", "w") as f:
    json.dump(scores, f, indent=2)

Load, modify the Python list with append, then dump it back. This load-change-save cycle is how most apps store user data.

Common mistakes

  • Mixing up the s versions. Using json.load on a string (instead of json.loads) raises an error, and vice versa.
  • Forgetting to import json. The module is built in, but you still need import json.
  • Expecting JSON to store everything. Sets, custom objects and functions are not valid JSON. Convert a set to a list first, for example.
  • Single quotes in a JSON file. JSON requires double quotes around keys and strings. The module produces these correctly, but if you edit a file by hand, do not switch to single quotes.

Try it yourself

  1. Save a dictionary describing yourself (name, age, hobbies as a list) to me.json, then load it and print each hobby.
  2. Write a function add_score(name, points) that loads scores.json, appends a new entry and saves it again.
  3. Load scores.json and print only the players with more than 100 points, using the comparison skills from Python comparison and logic.

Once you can move data in and out of files, try the related challenge of tabular data in working with CSV data in Python.

Quick quiz

Test yourself and earn XP

What does JSON stand for?

Which function turns a Python dictionary into a JSON string?

Which function reads JSON directly from an open file?

A JSON object maps to which Python type?

Why is the 's' in dumps and loads important?

FAQ

Use JSON when your data has structure - lists, dictionaries, nested values - and you want to load it back later without writing your own parser. For simple lines of text, a plain text file is fine.

No. JSON supports strings, numbers, booleans, null, lists and dictionaries. It cannot directly store custom class objects, sets, or functions; you must convert those into supported types first.

No. The json module is part of Python's standard library, so you only need to write import json at the top of your file.