Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 149 ยท Modules and the Standard Library

Working with JSON

Learn to read and write JSON in Python. Convert data with json.dumps and json.loads, save JSON files, pretty-print, handle errors and encode dates and classes.

JSON (JavaScript Object Notation) is the most common format for exchanging data between programs. Web APIs send it, configuration files use it, and many databases store it. It's plain text, easy for humans to read, and every major language can parse it.

Python's built-in json module converts between JSON text and ordinary Python objects: dictionaries, lists, strings, numbers, booleans and None. In this lesson you'll convert in both directions, save and load JSON files, control the output format, deal with bad input, and teach the module about types it doesn't know, such as dates.

What JSON looks like

JSON has only a few building blocks, and each maps to a Python type:

JSON Python
object {"key": value} dict
array [1, 2, 3] list
string "text" str
number 42, 3.5 int, float
true / false True / False
null None

It looks a lot like Python literals, but the rules are stricter: strings and keys must use double quotes, object keys must be strings, there are no trailing commas, and no comments.

JSON
{
  "name": "Riverside Library",
  "open": true,
  "rating": 4.6,
  "branches": ["North", "Harbor"],
  "manager": null
}

Python to JSON: json.dumps()

json.dumps() ("dump to string") turns Python data into JSON text:

Python dumps basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice the conversions: True became true, None became null, the tuple became an array, and the integer key 42 became the string "42". That last one matters: a round trip through JSON gives you {"42": ...}, not {42: ...}.

Formatting options

A few keyword arguments control the output:

Python indent, sort_keys, separators, ensure_ascii

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

  • indent=2 pretty-prints for humans; leave it out for compact output sent over a network.
  • sort_keys=True produces stable output, handy for tests and version control diffs.
  • separators=(",", ":") removes all optional spaces.
  • ensure_ascii=False keeps characters like รซ readable instead of รซ. Both forms are valid JSON.

JSON to Python: json.loads()

json.loads() ("load from string") parses JSON text into Python objects. You then work with ordinary dictionaries and lists:

Python Parsing JSON text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Real-world JSON can be missing fields, so use dict.get() with a default for anything optional: day.get("wind", 0).

Handling invalid JSON

When the text isn't valid JSON, loads() raises json.JSONDecodeError, a subclass of ValueError. Its message tells you the line and column of the problem:

Python Catching JSONDecodeError

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Never "fix" JSON with eval(). Data from outside your program can contain code, and eval() would run it. Parse with json.loads() and handle the error.

Reading and writing JSON files

For files, use json.dump() and json.load() (no "s"): they write to and read from an open file object instead of a string. The browser runner has an in-memory file system, so this works here too:

Python Save and load a JSON file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Always open JSON files with encoding="utf-8": the JSON standard requires UTF-8, and your operating system's default may differ. The lessons on files and pathlib cover file handling in depth; Path("tasks.json").write_text(json.dumps(...)) is a handy one-liner too.

Function Direction Works with
json.dumps(obj) Python โ†’ JSON a string
json.loads(text) JSON โ†’ Python a string
json.dump(obj, file) Python โ†’ JSON a file
json.load(file) JSON โ†’ Python a file

Types JSON doesn't support

JSON has no dates, sets, decimals or custom classes. Try to dump one and you get a TypeError. There are two clean ways to handle this.

The default function

Pass default= a function. dumps() calls it for any object it can't handle; return something JSON-friendly, or raise TypeError to refuse:

Python Encoding dates, sets and objects with default=

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You can also subclass json.JSONEncoder and override its default() method, then pass cls=YourEncoder. It does the same thing; a plain function is usually simpler.

Decoding back with object_hook

On the way back, JSON gives you strings, not dates. object_hook is called with every decoded object (dictionary), and whatever it returns replaces that dictionary. Use it to rebuild richer types:

Python object_hook

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For bigger projects with many types, validation libraries such as Pydantic map JSON to classes automatically, but default and object_hook are enough for most scripts.

Reading JSON from the web

Most of the JSON you meet comes from web APIs. With the third-party requests package, response.json() calls json.loads() for you; with the standard library, you read the response body and parse it yourself:

Python
import json
from urllib.request import urlopen

with urlopen("https://api.example.com/v1/status") as response:
    data = json.load(response)       # a response works like a file

print(data["status"])

The editors on this page can't make requests to arbitrary servers, so try this on your computer with a real API. Whatever the source, the pattern stays the same: parse once at the edge of your program, then work with ordinary dictionaries and lists everywhere else.

A few gotchas

  • Floats: json.loads("0.1") gives a float with the usual precision issues. For money, pass parse_float=Decimal.
  • Big or special numbers: Python happily writes NaN and Infinity, which aren't valid JSON. Pass allow_nan=False to get an error instead of output other systems can't read.
  • Duplicate keys: if JSON text repeats a key, the last value wins silently.
  • Not JSON Lines: json.load() expects one JSON document per file. For files with one object per line, loop over the lines and call json.loads() on each.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does json.dumps({"active": True, "id": None}) return?

    dumps() returns a string of valid JSON, so True becomes true, None becomes null, and keys get double quotes.
  2. 2. Which function reads JSON from an open file object?

    load and dump work with files; loads and dumps (with an s for string) work with strings.
  3. 3. You dump {1: "a"} to JSON and load it back. What do you get?

    JSON object keys are always strings, so the integer key comes back as the string "1".
  4. 4. json.dumps({"day": date(2026, 1, 1)}) raises TypeError. What's the simplest fix?

    default is called for objects JSON can't encode; returning an ISO string makes the date serializable.
  5. 5. Parsing {'name': 'Kai'} with json.loads() fails. Why?

    Single quotes are valid in Python but not in JSON, so loads() raises JSONDecodeError.

Summary

  • JSON objects, arrays, strings, numbers, true/false and null map to dict, list, str, int/float, True/False and None.
  • dumps()/loads() work with strings; dump()/load() work with files (open them with encoding="utf-8").
  • indent, sort_keys, separators and ensure_ascii control the output format.
  • Invalid input raises json.JSONDecodeError; never use eval() on data.
  • Use default= to encode dates, sets, decimals and objects, and object_hook= to rebuild them when loading.

Next: Saving Objects with pickle and shelve.