Home / Python / Example programs / Files and data

Python program: Save and load data as JSON

Store a list of records in a JSON file and read it back.

The code

import json

contacts = [
    {"name": "Sita", "phone": "0400 000 001", "tags": ["uni", "ai"]},
    {"name": "Leo", "phone": "0400 000 002", "tags": []},
]
with open("contacts.json", "w", encoding="utf-8") as f:
    json.dump(contacts, f, indent=2)

with open("contacts.json", encoding="utf-8") as f:
    loaded = json.load(f)
print(loaded == contacts)
print(open("contacts.json", encoding="utf-8").read()[:80])

Output

True
[
  {
    "name": "Sita",
    "phone": "0400 000 001",
    "tags": [
      "uni"

How it works

json.dump writes Python lists and dictionaries as JSON text, and json.load reads them back unchanged. indent=2 makes the file easy for people to read.

Python features used

Learn the ideas behind it in the free lesson Files.