Skip to content

Module 13 · File Handling — topic 11 of 15

JSON files

Storing structured data with the json module: dump and load for files, dumps and loads for strings, how Python types map to JSON, pretty-printing, non-ASCII text and handling invalid JSON.

Beginner 10 min read·Lesson 204 of 306 in Python Programming

Learning objectives

  • Save and load data with json.dump and json.load
  • Know how Python types map to JSON
  • Handle invalid JSON and missing files

Definition

JSON (JavaScript Object Notation) is a text format for structured data made of objects, arrays, strings, numbers, booleans and null. The json module converts between JSON text and Python dictionaries, lists and values.

Introduction

Settings, saved games and web API responses are usually JSON. It maps naturally onto Python dictionaries and lists, so saving structured data takes one line.

Why it matters

JSON is the lingua franca of the web and of configuration files. Being able to read and write it is essential for real projects.

Detailed explanation

json.dump(obj, f) writes obj to an open file; json.load(f) reads it back. dumps and loads (with an s for 'string') work with strings instead.

Type mapping: dict ↔ object, list/tuple → array, str ↔ string, int/float ↔ number, True/False ↔ true/false, None ↔ null. Tuples come back as lists.

JSON object keys are always strings; integer keys become strings when saved.

indent=2 produces readable, indented output; sort_keys=True orders keys; ensure_ascii=False keeps non-English characters readable instead of \u escapes.

Only basic types are supported. Sets, dates and custom objects raise TypeError unless you convert them (for example to lists or ISO date strings).

Invalid JSON raises json.JSONDecodeError (a subclass of ValueError) with the message, line and column.

A common pattern merges loaded settings over defaults: {**DEFAULTS, **loaded}.

Syntax

Python
import json
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
with open("data.json", encoding="utf-8") as f:
data = json.load(f)
  • dump/load for files.
  • dumps/loads for strings.
  • indent for readability.

Code examples

Saving and loading

Python
import json
data = {"name": "Asha", "age": 30, "skills": ["python", "sql"], "active": True, "manager": None}
with open("user.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
with open("user.json", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded == data, loaded["skills"][0])
Output
True python

Python to JSON and back

Python
import json
print(json.dumps({"ok": True, "missing": None, "pair": (1, 2)}))
print(json.loads('{"ok": true, "n": 1.5}'))
Output
{"ok": true, "missing": null, "pair": [1, 2]}
{'ok': True, 'n': 1.5}

More examples

A settings store with defaults

Python
import json
DEFAULTS = {"theme": "light", "font_size": 14}
def load_settings(path):
try:
with open(path, encoding="utf-8") as f:
return {**DEFAULTS, **json.load(f)}
except FileNotFoundError:
return dict(DEFAULTS)
except json.JSONDecodeError as e:
print("corrupt settings:", e.msg)
return dict(DEFAULTS)
def save_settings(path, settings):
with open(path, "w", encoding="utf-8") as f:
json.dump(settings, f, indent=2, ensure_ascii=False, sort_keys=True)
print(load_settings("settings.json"))
s = load_settings("settings.json")
s["theme"] = "dark"
s["greeting"] = "नमस्ते"
save_settings("settings.json", s)
print(load_settings("settings.json"))
with open("settings.json", "w", encoding="utf-8") as f:
f.write("{broken")
print(load_settings("settings.json"))
Output
{'theme': 'light', 'font_size': 14}
{'theme': 'dark', 'font_size': 14, 'greeting': 'नमस्ते'}
corrupt settings: Expecting property name enclosed in double quotes
{'theme': 'light', 'font_size': 14}

Step-by-step explanation

  • A missing file simply means 'use the defaults'.
  • Saved values override defaults when merged, and new keys are kept.
  • ensure_ascii=False stores the Hindi greeting as readable text; a corrupt file is reported and the defaults are used.

Expected output

Running “A settings store with defaults” prints exactly:

TextOutput
{'theme': 'light', 'font_size': 14}
{'theme': 'dark', 'font_size': 14, 'greeting': 'नमस्ते'}
corrupt settings: Expecting property name enclosed in double quotes
{'theme': 'light', 'font_size': 14}

Practical applications

  • Application settings and saved state.
  • Data exchanged with web APIs.

Best practices

  • Use indent for files people may read.
  • Handle FileNotFoundError and JSONDecodeError.
  • Convert dates and sets explicitly.

Common mistakes

Saving unsupported types

Avoid

json.dump({"tags": {"a", "b"}}, f)

Prefer

json.dump({"tags": sorted({"a", "b"})}, f)

Sets aren't JSON-serialisable; convert them to lists.

Confusing dump and dumps

Avoid

f.write(json.dump(data))

Prefer

json.dump(data, f) # or f.write(json.dumps(data))

dump writes to a file and returns None; dumps returns a string.

Important notes

  • json.dumps(obj, default=str) converts unknown types with str() as a quick fallback.

Key takeaways

  • json.dump/load for files, dumps/loads for strings.
  • dict↔object, list↔array, None↔null.
  • Invalid JSON raises JSONDecodeError.

Try it yourself

  1. 1
    Save a list of contacts (name, phone, tags) to JSON and load it back.
  2. 2
    Write a high-score file that keeps the top five scores between runs.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic