Python

Python JSON — dumps, loads, and Files

JSON is the text format most APIs, config files, and data files share, and Python ships with a module that speaks it directly. One call turns a dict into JSON text you can send or store, and the mirror call turns text back into dicts, lists, strings, and numbers you can work with. This guide builds each direction, controls the layout of the text, works with files, reads nested data, and shows the two errors that turn up first, with a small working program for each step and the exact output it prints.

Written November 12, 2026 · Tested with Python 3.12.3 · 11 min read

By the end of this guide
  • The main program: dumps writes text, loads reads it back
  • indent, sortkeys, and separators control the layout
  • Types change at the border
  • dump and load work on files

Written November 12, 2026

Tested with Python 3.12.3

What this guide is

The json module moves data between two forms. On one side are Python values: dicts, lists, strings, numbers, True, False, and None. On the other side is JSON text: a string that follows a fixed grammar, with objects in braces, arrays in brackets, and names in double quotes. The dumps function writes Python values as JSON text, and loads reads JSON text back into Python values. The names carry a hint: dumps dumps to a string, and loads loads from a string. Two file versions drop the final s, and the file section below covers them. Most work with JSON is one of those four calls, plus reading the values that come back.

The main program: dumps writes text, loads reads it back

Build a dict, turn it into JSON text, and parse that text back. The two forms print differently, because JSON spells some values in its own way:

Python
import json

record = {"name": "ana", "age": 31, "admin": False, "tags": ["dev", "ops"], "score": 9.5, "nickname": None}
text = json.dumps(record)
print(text)
print(type(text).__name__)
back = json.loads(text)
print(back)
print(type(back).__name__)
print(back["name"], back["age"], back["admin"], back["nickname"])
print(back == record)

The exact output:

Output
{"name": "ana", "age": 31, "admin": false, "tags": ["dev", "ops"], "score": 9.5, "nickname": null}
str
{'name': 'ana', 'age': 31, 'admin': False, 'tags': ['dev', 'ops'], 'score': 9.5, 'nickname': None}
dict
ana 31 False None
True

The first line is a string, even though it prints like a dict. JSON writes false in lowercase and None as null, and it puts double quotes around every key. The loads call parses that text and hands back a real dict, with Python spellings restored: False is False again, and null is None again. The last line compares the parsed dict with the original and returns True, so this record round-trips without loss. That round trip is the test most JSON code relies on: if a value survives dumps and then loads and still compares equal, the text held everything the value held.

indent, sort_keys, and separators control the layout

The default dumps output is one line, which suits a network call or a log line. Three arguments change the layout without changing the data:

Python
import json

record = {"name": "ana", "age": 31}
print(json.dumps(record, indent=2))
print(json.dumps(record, sort_keys=True))
data = {"b": 1, "a": 2, "c": 3}
print(json.dumps(data, sort_keys=True))
print(json.dumps(data, separators=(",", ":")))
print(json.dumps({"city": "Montréal"}, ensure_ascii=False))
print(json.dumps({"city": "Montréal"}))

The exact output:

Output
{
  "name": "ana",
  "age": 31
}
{"age": 31, "name": "ana"}
{"a": 2, "b": 1, "c": 3}
{"b":1,"a":2,"c":3}
{"city": "Montréal"}
{"city": "Montr\u00e9al"}

An indent of 2 puts each key on its own line with two spaces of padding, which is the layout to pick for a file a person will read or a diff a person will review. The sort_keys argument orders keys by name instead of by insertion order, so two dicts with the same pairs produce the same text, and tests that compare text stop depending on build order. The separators argument drops the spaces after the colon and the comma, which gives the smallest plain form. The last two lines show the ensure_ascii switch. By default dumps escapes a non-ASCII character as a unicode code point, which keeps the text pure ASCII and safe for any reader. Passing ensure_ascii=False writes the character itself, which reads better and still parses back to the same string, as long as the reader and the file agree on UTF-8.

Types change at the border

JSON has fewer types than Python, so some values change shape on the way out and do not change back:

Python
import json

print(json.dumps((1, 2)))
print(json.loads("[1, 2]"))
print(json.dumps({1: "a", 2: "b"}))
loaded = json.loads('{"1": "a", "2": "b"}')
print(loaded)
print([type(k).__name__ for k in loaded])
print(json.loads("42"), type(json.loads("42")).__name__)
print(json.loads("4.5"), type(json.loads("4.5")).__name__)
print(json.loads("true"), json.loads("null"))

The exact output:

Output
[1, 2]
[1, 2]
{"1": "a", "2": "b"}
{'1': 'a', '2': 'b'}
['str', 'str']
42 int
4.5 float
True None

A tuple dumps as a JSON array, and an array loads as a list, so a tuple comes back as a list. A dict with integer keys dumps with those keys written as strings, because JSON object names are always strings, and the keys load back as strings. Code that indexes a loaded dict with an integer will miss every key; convert the keys back yourself if the original dict used integers. Numbers split by their text form: a whole number loads as an int, and a number with a decimal point loads as a float. The last line parses two bare JSON values, which loads accepts at the top level just as it accepts an object or an array.

dump and load work on files

The file versions take an open file as a second argument. The dump function writes to the file, and load reads from it, so no string sits in between:

Python
import json
from pathlib import Path

record = {"name": "ana", "age": 31}
path = Path("data.json")
with path.open("w", encoding="utf-8") as f:
    json.dump(record, f, indent=2)
print(path.read_text(encoding="utf-8"))
with path.open(encoding="utf-8") as f:
    back = json.load(f)
print(back)
print(back["age"] + 1)

The exact output:

Output
{
  "name": "ana",
  "age": 31
}
{'name': 'ana', 'age': 31}
32

The file holds exactly the indented text the formatting section produced, and load hands back the dict, ready for arithmetic on its values. The indent argument works here the same way it works on dumps, and the encoding matters for the same reason it mattered in the ensure_ascii lines: a file that may hold names like Montréal should be opened as UTF-8 on both the write and the read. One shape covers most local data: build a dict or a list, dump it once, and load it wherever the program needs it again. A program that appends to a JSON file instead should read the whole file, change the list, and write the whole file back, because JSON text has no append form that a later load can parse as one value.

Nested data reads one level at a time

Real JSON nests. An object holds another object, which holds an array, and each level reads with the ordinary dict and list syntax:

Python
import json

text = '{"user": {"name": "ana", "roles": ["dev", "ops"]}, "count": 2}'
data = json.loads(text)
print(data["user"]["name"])
print(data["user"]["roles"][1])
print(data["count"])
data["count"] = 3
data["user"]["roles"].append("lead")
print(json.dumps(data))
print(json.dumps(data["user"], indent=2))

The exact output:

Output
ana
ops
2
{"user": {"name": "ana", "roles": ["dev", "ops", "lead"]}, "count": 3}
{
  "name": "ana",
  "roles": [
    "dev",
    "ops",
    "lead"
  ]
}

Each bracket moves one level in: the first key picks the inner dict, the next key picks a value inside it, and an index picks an item from a list. Once the text is loaded, there is no JSON left to handle; the value is plain dicts and lists, and the same code that walks any nested structure walks this one. The edits in the middle work for the same reason, and the dumps call at the end writes the changed structure back as one line. The last call dumps only the inner dict, which is a handy way to print one part of a large response while you work out its shape.

Numbers keep their kind

A loaded number is ready to use, and its kind follows the text it came from:

Python
import json

text = '{"count": 3, "price": 9.5, "big": 12345678901234567890}'
data = json.loads(text)
print(data)
print(type(data["count"]).__name__, type(data["price"]).__name__)
print(data["count"] + 1, data["price"] * 2)
print(json.dumps(data))
print(json.loads("[1, 2, 3]")[0])

The exact output:

Output
{'count': 3, 'price': 9.5, 'big': 12345678901234567890}
int float
4 19.0
{"count": 3, "price": 9.5, "big": 12345678901234567890}
1

A count written without a decimal point loads as an int, so adding one stays an int. A price written with one loads as a float, so doubling it gives a float, printed here as 19.0. A long whole number loads as an int with every digit intact, because Python ints have no fixed size limit. The dumps call writes the dict back with the same digits, so a value that arrived as text, was read as a number, and leaves as text again keeps its form. Money code that needs exact decimal places should still reach for a decimal type rather than a float; JSON parsing by itself gives you the float.

Two errors cover most failures

Bad text fails at loads, and a value JSON cannot represent fails at dumps. Both errors name the problem:

Python
import json

try:
    json.loads('{"name": }')
except json.JSONDecodeError as e:
    print(type(e).__name__)
    print(e.msg)
    print(e.pos, e.lineno, e.colno)
try:
    json.dumps({1, 2})
except TypeError as e:
    print(type(e).__name__)
    print(e)
print(json.dumps(sorted({1, 2})))

The exact output:

Output
JSONDecodeError
Expecting value
9 1 10
TypeError
Object of type set is not JSON serializable
[1, 2]

The first text stops where a value should follow the colon. JSONDecodeError carries the position as a character offset, a line number, and a column number, which is enough to point at the bad spot in a file. The error is a subclass of ValueError, so code that already catches ValueError around parsing catches this too. The second failure is the other direction: a set has no JSON form, so dumps raises TypeError and names the type. The fix is a conversion at the border, here sorting the set into a list, which also gives the array a stable order. Dates and other custom objects fail the same way, and they take the same fix: turn the value into a dict, a list, a string, or a number before dumps sees it.

Which tool for which job

Job Tool Why
Turn a value into JSON text in memory dumps The result is a string you can send, store, or compare
Read JSON text you already hold loads The text becomes dicts and lists you can index
Write a value straight to a file dump with an open file No string sits in between, and indent shapes the file
Read a value straight from a file load with an open file The file becomes a Python value in one call
Make a file a person will read indent=2 Each key gets its own line
Make two equal dicts produce equal text sort_keys=True Key order stops depending on insertion order
Make the smallest plain text separators=(",", ":") The spaces after commas and colons come out
Keep a non-ASCII character as itself ensure_ascii=False, with UTF-8 files The character writes as itself instead of an escape
Find where bad text broke JSONDecodeError pos, lineno, and colno The error points at the failing spot
Send a set or a date through JSON Convert to a list or a string first dumps raises TypeError on types JSON has no form for

Checklist

  • Before indexing a loaded dict with an integer key, remember the keys came back as strings; convert them if the code needs integers.
  • Before comparing a round trip for equality, check for tuples and sets, which come back as lists or fail outright.
  • Before writing a file that may hold non-ASCII text, open it as UTF-8 on the write and on the read.
  • Before appending to a JSON file, load the whole value, change it, and write the whole value back.
  • Before trusting text from another program, parse it in a try block and read the position fields on JSONDecodeError.
  • Before passing a value to dumps, turn sets, dates, and custom objects into lists, strings, or dicts.

Sources

  • Python Standard Library, json — the dumps, loads, dump, and load documentation this guide follows, including the type conversion table, the indent, sort_keys, separators, and ensure_ascii arguments, and the JSONDecodeError fields.
  • Python Tutorial, Input and Output — the tutorial section that introduces saving structured data with json alongside file reading and writing.

Keep Exploring