PythonMastery
Python programs · Files · beginner

Read and write a JSON file in Python

Save a dictionary to a JSON file with json.dump() and load it back with json.load(). Shows which Python types survive the round trip.

JSON is a text format for data made of objects, lists, strings, numbers, true/false and null. It maps closely to Python dictionaries and lists, and the json module converts between the two.

The program

python
import json

profile = {
    "name": "Hedy",
    "age": 35,
    "languages": ["Python", "SQL"],
    "active": True,
    "manager": None,
}

with open("profile.json", "w", encoding="utf-8") as f:
    json.dump(profile, f, indent=2)

with open("profile.json", encoding="utf-8") as f:
    print(f.read())

with open("profile.json", encoding="utf-8") as f:
    loaded = json.load(f)

print(loaded)
print("Same data:", loaded == profile)
output
{
  "name": "Hedy",
  "age": 35,
  "languages": [
    "Python",
    "SQL"
  ],
  "active": true,
  "manager": null
}
{'name': 'Hedy', 'age': 35, 'languages': ['Python', 'SQL'], 'active': True, 'manager': None}
Same data: True

How it works

Types that change

Not every Python type has a JSON form. A tuple is saved as a JSON list, so it comes back as a list. Dictionary keys must be strings, so a number key comes back as a string:

python
import json

data = {"point": (3, 4), 1: "one"}
text = json.dumps(data)
print(text)
print(json.loads(text))
output
{"point": [3, 4], "1": "one"}
{'point': [3, 4], '1': 'one'}

A set or a datetime cannot be saved directly: json.dumps() raises TypeError. Convert them first, for example with list(my_set) or my_date.isoformat().

Learn the idea: CSV, JSON, and JSONL: Structured Text Done Right, Dictionaries

A longer explanation: How do I read a JSON file in Python?