Python Files, Paths, CSV and JSON · Lesson 108 of 149

Python JSON

What you will learn

  • What JSON is and how it maps to Python types
  • dumps / loads for strings, dump / load for files
  • Pretty printing: indent, sort_keys, ensure_ascii
  • Handling JSONDecodeError
  • What JSON cannot store, and default=
  • Using JSON for settings and for data exchange

1. What is JSON?

JSON (JavaScript Object Notation) is a text format for structured data: nested objects, lists, text, numbers and truth values. It is the standard way programs and websites exchange data, and a popular format for settings files. It looks much like a Python dictionary:

{"name": "Rina", "age": 25, "scores": [80, 90.5], "active": true, "address": null}

Python's standard json module converts between JSON text and Python objects:

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

JSON has strict rules: strings use double quotes only, no trailing commas, no comments.

2. Python to JSON text: dumps

json.dumps(obj) ("dump to string") returns JSON text:

import json

data = {"name": "Rina", "age": 25, "scores": [80, 90.5], "active": True,
        "address": None, "tags": ("a", "b")}
s = json.dumps(data)
print(s)
print(type(s))
{"name": "Rina", "age": 25, "scores": [80, 90.5], "active": true, "address": null, "tags": ["a", "b"]}
<class 'str'>

True became true, None became null, and the tuple became a list.

Options for readability:

print(json.dumps(data, indent=2))
print(json.dumps(data, sort_keys=True, separators=(",", ":")))
{
  "name": "Rina",
  "age": 25,
  "scores": [
    80,
    90.5
  ],
  "active": true,
  "address": null,
  "tags": [
    "a",
    "b"
  ]
}
{"active":true,"address":null,"age":25,"name":"Rina","scores":[80,90.5],"tags":["a","b"]}
  • indent=2 pretty-prints with 2-space indentation, for humans.
  • sort_keys=True orders the keys alphabetically (useful for comparing files).
  • separators=(",", ":") removes spaces for the most compact output.

Non-English text

By default, non-ASCII characters are written as \u escapes. Add ensure_ascii=False to keep them readable (and save with UTF-8):

print(json.dumps("café ঢাকা"))
print(json.dumps("café ঢাকা", ensure_ascii=False))
"caf\u00e9 \u09a2\u09be\u0995\u09be"
"café ঢাকা"

Both are valid JSON that read back identically.

Quick check: what does `json.dumps(None)` return?

The string 'null'.

3. JSON text to Python: loads

json.loads(text) ("load from string") parses JSON text back into Python objects:

back = json.loads(s)
print(back)
print(type(back["scores"]), back["active"], back["address"])
print(back["tags"], type(back["tags"]))
{'name': 'Rina', 'age': 25, 'scores': [80, 90.5], 'active': True, 'address': None, 'tags': ['a', 'b']}
<class 'list'> True None
['a', 'b'] <class 'list'>

The tuple did not survive: it came back as a list, because JSON has no tuples. So loads(dumps(x)) == x holds only for data made of JSON types. json.loads can also parse single values:

print(json.loads('{"1": "a"}'), json.loads('[1, 2.0, "x", null, true]'), json.loads("42"), json.loads('"hi"'))
{'1': 'a'} [1, 2.0, 'x', None, True] 42 hi

4. Files: dump and load

Without the s, the functions work with file objects (lesson 15.1):

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

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

print(loaded == data, loaded["tags"])
False ['a', 'b']

The comparison is False only because data holds a tuple and loaded holds a list. Remember the pair: dump/load use files, dumps/loads use strings (the s stands for string). With pathlib (lesson 15.4) you can combine the string versions:

from pathlib import Path
Path("p.json").write_text(json.dumps(data), encoding="utf-8")
loaded = json.loads(Path("p.json").read_text(encoding="utf-8"))

5. Bad JSON: JSONDecodeError

Input that is not valid JSON raises json.JSONDecodeError, a kind of ValueError, with the position of the problem:

for bad in ["{'a': 1}", '{"a": 1,}', "", "nope"]:
    try:
        json.loads(bad)
    except json.JSONDecodeError as e:
        print("JSONDecodeError:", e.msg, "| line", e.lineno, "col", e.colno)
JSONDecodeError: Expecting property name enclosed in double quotes | line 1 col 2
JSONDecodeError: Illegal trailing comma before end of object | line 1 col 8
JSONDecodeError: Expecting value | line 1 col 1
JSONDecodeError: Expecting value | line 1 col 1

Common causes: single quotes, a trailing comma, an empty file, and text that is not JSON at all. Always expect that files and web responses may be damaged, and catch the error (lesson 14.1).

6. What JSON cannot store

JSON supports only the types in the table. Other Python values fail:

json.dumps({"s": {1, 2}})
TypeError: Object of type set is not JSON serializable
import datetime
json.dumps({"d": datetime.date(2026, 3, 1)})
TypeError: Object of type date is not JSON serializable

Solutions:

  1. Convert before saving: sets to sorted lists, dates to text with isoformat(), dataclasses with asdict (lesson 13.11), enums to .value (lesson 13.12).
  2. Give dumps a default= function, called for anything it does not know:
print(json.dumps({"d": datetime.date(2026, 3, 1)}, default=str))
{"d": "2026-03-01"}
  1. For many types, write an encoder class:
class Enc(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, set):
            return sorted(o)
        return super().default(o)

print(json.dumps({"s": {3, 1, 2}}, cls=Enc))
{"s": [1, 2, 3]}

Loading goes the other way: the date comes back as text, and you convert it yourself. And dataclasses:

from dataclasses import dataclass, asdict

@dataclass
class P:
    name: str
    age: int

print(json.dumps(asdict(P("Rina", 25))))
print(P(**json.loads('{"name": "Sam", "age": 22}')))
{"name": "Rina", "age": 25}
P(name='Sam', age=22)

Other surprises

  • Keys become strings. Numbers, True and None used as keys are converted, and keys that become equal collide:
print(json.dumps({1: "a", 2.5: "b", True: "c", None: "d"}))
{"1": "c", "2.5": "b", "null": "d"}

(1 and True are equal in Python, so only one key remained, with the later value "c".) After loading, a key 1 is the string "1".

  • Duplicate keys: json.loads('{"a": 1, "a": 2}') silently keeps the last, {'a': 2}.
  • Floats: json.dumps(0.1 + 0.2) writes 0.30000000000000004, the same as Python prints (lesson 3.4). Big integers are kept exactly: 10**20 becomes 100000000000000000000.
  • NaN is written as NaN, which is not valid JSON for many other programs; avoid it.
  • Never use JSON from an untrusted source as code. json.loads only builds data, so it is safe to parse (unlike pickle, lesson 15.8).

7. Navigating loaded data

Loaded JSON is ordinary dictionaries and lists, so use the tools from earlier chapters (lesson 9.4):

cfg = json.loads('{"db": {"host": "localhost", "ports": [5432, 5433]}, "debug": false}')
print(cfg["db"]["ports"][1])
print(cfg.get("debug"), cfg.get("missing", "default"))
5433
False default

Use .get with a default for keys that may be missing. For very large data made of many records, one JSON object per line (JSON Lines) can be read line by line with json.loads(line), avoiding loading the whole file.

Worked example: an application settings file

An app keeps settings.json. The loader starts from defaults, overlays whatever the file has, and survives a missing or damaged file. Saving writes readable JSON.

import json
from pathlib import Path

PATH = Path("settings.json")


def defaults():
    return {"theme": "light", "font_size": 12, "recent": []}


def load_settings():
    try:
        saved = json.loads(PATH.read_text(encoding="utf-8"))
    except FileNotFoundError:
        return defaults()
    except json.JSONDecodeError as e:
        print(f"settings file damaged (line {e.lineno}): using defaults")
        return defaults()
    return {**defaults(), **saved}


def save_settings(settings):
    PATH.write_text(json.dumps(settings, indent=2, ensure_ascii=False) + "\n",
                    encoding="utf-8")


s = load_settings()
print(s)
s["theme"] = "dark"
s["recent"].append("notes.txt")
save_settings(s)
print(PATH.read_text(encoding="utf-8"), end="")
print(load_settings() == s)

PATH.write_text('{"theme": "dark", "font_size": 14,}', encoding="utf-8")
print(load_settings())

PATH.write_text('{"font_size": 16}', encoding="utf-8")
print(load_settings())
PATH.unlink()
{'theme': 'light', 'font_size': 12, 'recent': []}
{
  "theme": "dark",
  "font_size": 12,
  "recent": [
    "notes.txt"
  ]
}
True
settings file damaged (line 1): using defaults
{'theme': 'light', 'font_size': 12, 'recent': []}
{'theme': 'light', 'font_size': 16, 'recent': []}
Step Idea
defaults() is a function each call returns a fresh dictionary and list, avoiding the shared mutable default trap (lesson 11.9)
{**defaults(), **saved} the saved values win; missing keys fall back to defaults (lesson 9.5)
except FileNotFoundError first run: no file yet
except json.JSONDecodeError a damaged file is reported, not fatal
indent=2 and a final newline a file that humans can read and edit

The settings are made up. A real program would also validate the values (for example that font_size is a number).

Common mistakes

  • Confusing dump/load (files) with dumps/loads (strings).
  • Writing JSON by hand with single quotes or trailing commas.
  • Expecting tuples, sets, dates or custom objects to round-trip.
  • Forgetting that keys become strings.
  • Not catching JSONDecodeError for files or web data.
  • Forgetting encoding="utf-8" (and ensure_ascii=False when you want readable text).
  • Keeping a mutable default that is shared between uses.
  • Using eval instead of json.loads on JSON text.

Key takeaways

  • JSON maps to dict, list, str, numbers, bool and None.
  • dumps/loads convert strings; dump/load use open files.
  • indent, sort_keys and ensure_ascii=False control the layout.
  • Bad input raises JSONDecodeError (a ValueError); catch it.
  • Convert unsupported types (sets, dates, dataclasses) before saving or use default=.
  • Dictionary keys always become strings in JSON.

Practice

1. What is the difference between json.dump and json.dumps?

Show answer

dump writes JSON to an open file; dumps returns the JSON as a string.

2. What does json.loads('{"a": [1, true, null]}') return?

Show answer

{'a': [1, True, None]}

3. Why does json.loads("{'a': 1}") fail?

Show answer

JSON requires double quotes; single quotes are invalid, so it raises JSONDecodeError.

4. How can you save a dictionary that contains a set?

Show answer

Convert the set to a list first (for example sorted(s)), or use default= or an encoder class that does it.

5. After json.loads(json.dumps({1: "a"})), what is the key?

Show answer

The string "1". JSON object keys are always strings.

6. Write the code that saves data to out.json, pretty-printed and with readable non-English text.

Show answer
with open("out.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2, ensure_ascii=False)