Python JSON Module Explained: dumps, loads, Custom Types and Common Errors
JSON is how most programs exchange data, and Python’s built-in json module reads and writes it in one line. The details matter, though: dates, decimals, number keys and floats all change on the way through. We tested each case.
json.dumpsturns Python objects into a JSON string;json.loadsturns JSON back into Python.dumpandloaddo the same with files.- Tuples become lists and integer dictionary keys become strings, so a round trip is not always identical.
- Dates, Decimals, sets and UUIDs raise
TypeError; handle them withdefault=or a custom encoder. - Use
parse_float=Decimalfor money, and validate parsed data before trusting it.
An API returns order data, a config file stores settings, a test fixture holds expected results: all of them are probably JSON. The Python JSON module is built in, fast and easy to start with, but its edge cases show up the first time you try to save a date, a Decimal or a dictionary with number keys.
We ran every example below with Python 3.13, and the outputs are from that run.
What is JSON?
JSON, JavaScript Object Notation, is a text format for structured data: objects (key-value pairs), arrays, strings, numbers, true, false and null. It is the standard format for web APIs, and it is easy for humans to read. Its rules are strict: keys must be strings in double quotes, no trailing commas and no comments.
dumps and loads
import json
data = {"id": 7, "name": "Asha", "tags": ["admin"], "active": True, "score": None, "price": 10.5}
s = json.dumps(data)
print(s)
# {"id": 7, "name": "Asha", "tags": ["admin"], "active": true, "score": null, "price": 10.5}
back = json.loads(s)
# types: id int, name str, tags list, active bool, score NoneType, price float
Notice True became true and None became null; on the way back, they returned to their Python forms. The “s” in dumps and loads stands for “string”.
Type mapping
| Python | JSON | Back to Python |
|---|---|---|
dict |
object | dict |
list, tuple |
array | list |
str |
string | str |
int, float |
number | int or float |
True/False |
true/false |
True/False |
None |
null |
None |
date, Decimal, set, UUID |
Not supported | TypeError on dumps |
What changes on the way through
json.loads(json.dumps({"p": (1, 2)})) # {'p': [1, 2]}
json.loads(json.dumps({1: "one", 2: "two"})) # {'1': 'one', '2': 'two'}
json.loads('{"a": 1, "a": 2}') # {'a': 2}
A tuple came back as a list, and integer keys came back as strings, because JSON object keys are always strings. Code that later looks up data[1] will get a KeyError, a common bug when caching dictionaries as JSON. A document with a duplicate key was accepted silently, with the last value winning. Treat a JSON round trip as a conversion, not a perfect copy.
Formatting output
json.dumps({"b": 1, "a": [1, 2]}, indent=2, sort_keys=True)
# {
# "a": [
# 1,
# 2
# ],
# "b": 1
# }
json.dumps({"a": 1, "b": [1, 2]}, separators=(",", ":"))
# {"a":1,"b":[1,2]}
Use indent for files people read, such as configuration or test fixtures, and sort_keys=True so that diffs in version control stay small and stable. Use compact separators to save bytes when sending data over the network.
Unicode
json.dumps({"note": "नमस्ते"})
# {"note": "नमस्ते"}
json.dumps({"note": "नमस्ते"}, ensure_ascii=False)
# {"note": "नमस्ते"}
By default, every non-ASCII character is escaped. Both forms are valid JSON and decode to the same text, but escaped output is hard to read and larger. Use ensure_ascii=False and write files with encoding="utf-8" for readable output.
Reading and writing files
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
with open(path, encoding="utf-8") as f:
loaded = json.load(f)
print(loaded == data) # True
Always pass an explicit encoding; on Windows the default may not be UTF-8. The with block closes the file even if writing fails, as explained in our context managers guide. For more on files, see Python file handling.
Dates, decimals and your own objects
Common types are not supported out of the box. Our tests raised:
TypeError: Object of type date is not JSON serializable
TypeError: Object of type Decimal is not JSON serializable
TypeError: Object of type set is not JSON serializable
TypeError: Object of type UUID is not JSON serializable
The simplest fix is a default function, which dumps calls for any object it cannot handle:
def default(o):
if isinstance(o, (datetime.date, datetime.datetime)): return o.isoformat()
if isinstance(o, decimal.Decimal): return str(o)
if isinstance(o, set): return sorted(o)
if dataclasses.is_dataclass(o): return dataclasses.asdict(o)
raise TypeError(f"not serializable: {type(o).__name__}")
json.dumps({"order": Order(101, Decimal("1180.50"), date(2026, 11, 11)),
"tags": {"b", "a"}}, default=default)
# {"order": {"id": 101, "total": "1180.50", "placed": "2026-11-11"}, "tags": ["a", "b"]}
Dates became ISO strings, the Decimal became a string to keep its exact value, the set became a sorted list, and the dataclass became a dictionary. Always end with raise TypeError, so unexpected types fail loudly instead of being silently turned into something wrong.
Decoding custom types back
class Enc(json.JSONEncoder):
def default(self, o):
if isinstance(o, datetime.date):
return {"__date__": o.isoformat()}
return super().default(o)
def hook(d):
return datetime.date.fromisoformat(d["__date__"]) if "__date__" in d else d
json.loads(json.dumps({"d": date(2026, 11, 11)}, cls=Enc), object_hook=hook)
# {'d': datetime.date(2026, 11, 11)}
A JSONEncoder subclass passed with cls= does the same job as default= in a reusable class. On the way back, object_hook is called for every decoded object, letting you turn tagged dictionaries back into dates or your own classes. For anything beyond a few types, a library such as Pydantic handles conversion and validation together, as shown in our structured output guide.
Tip: Agree on one date format for your whole system, normally ISO 8601 with a time zone, such as 2026-11-11T09:30:00+05:30 or UTC with a “Z”. Mixed formats across services cause far more bugs than JSON itself.
Floats and big numbers
json.loads("0.1") + json.loads("0.2") # 0.30000000000000004
json.loads("0.1", parse_float=Decimal) + json.loads("0.2", parse_float=Decimal) # 0.3
json.loads("12345678901234567890") # 12345678901234567890
JSON numbers become Python floats, with the usual binary rounding. For money, pass parse_float=decimal.Decimal, or send amounts as strings or whole numbers of the smallest unit. Python kept a 20-digit integer exactly, but JavaScript and many other languages cannot represent integers above 253 precisely, which is why large IDs are often sent as strings.
Python also writes NaN and Infinity by default, which are not valid JSON and will break other parsers. allow_nan=False makes this an error instead: “Out of range float values are not JSON compliant: nan”.
Parse errors
"{'a': 1}" Expecting property name enclosed in double quotes (line 1 col 2)
'{"a": 1,}' Illegal trailing comma before end of object (line 1 col 8)
'{"a": 1} extra' Extra data (line 1 col 10)
'' Expecting value (line 1 col 1)
'{"a": tru}' Expecting value (line 1 col 7)
Each bad input raised json.JSONDecodeError with a message and a position. The first case, single quotes, usually means someone pasted a Python dict‘s printout instead of real JSON. An empty string often means an API returned nothing, such as on an error, so check the HTTP status before parsing. Catch JSONDecodeError where input comes from outside your program.
JSON Lines for large data
lines = '{"id":1}\n{"id":2}\n'
[json.loads(l)["id"] for l in lines.splitlines()] # [1, 2]
json.load reads the whole document into memory. For logs and large exports, JSON Lines, one JSON object per line, can be processed one record at a time and appended to safely. It is the format used by many logging tools; see our Python logging guide for structured logs.
Validation and safety
json.loads is safe in the sense that it only creates basic data types; unlike some formats, it never runs code. But parsed data can still be wrong: missing fields, wrong types or huge payloads. Validate the shape with a schema or a model before using it, limit request sizes, and never pass JSON values straight into SQL or shell commands. Contract tests help keep the shape stable between services.
Speed and alternatives
The standard library’s json module is fast enough for most applications. When JSON handling shows up in profiling, for example in an API that serialises thousands of large responses per second, third-party libraries such as orjson and ujson are often several times faster, and orjson also handles dates and dataclasses natively. Measure before switching, since behaviour differs in small ways, such as how floats and non-string keys are handled.
JSON is not always the right format either:
- Configuration that people edit: TOML or YAML allow comments; see our YAML guide for its traps.
- Large analytical datasets: columnar formats such as Parquet are far smaller and faster to query.
- High-volume service traffic: binary formats such as Protocol Buffers or MessagePack are more compact and strictly typed.
For everyday APIs, logs and test fixtures, JSON’s readability and universal support usually win.
Final thoughts
The json module covers most needs with four functions. Remember what changes in a round trip, tuples to lists and integer keys to strings, handle dates and Decimals with a default function, use ensure_ascii=False and UTF-8 for readable files, and parse money with Decimal. Then validate what you load, because valid JSON is not the same as correct data.
Frequently asked questions
What is the difference between json.dumps and json.dump?
json.dumps returns a JSON string. json.dump writes JSON directly to a file object. Likewise, loads parses a string and load reads from a file.
How do I convert a datetime to JSON in Python?
Pass a default function to json.dumps that returns obj.isoformat() for dates and datetimes, or use a custom JSONEncoder subclass.
Why do my integer keys become strings?
JSON object keys must be strings, so json.dumps converts them. After loading, {1: “one”} becomes {“1”: “one”}.
How do I pretty-print JSON in Python?
Use json.dumps(data, indent=2), adding sort_keys=True for a stable order and ensure_ascii=False to keep non-English text readable.
Why do I get JSONDecodeError: Expecting value?
The input is empty or not valid JSON, often an error page or empty API response. Check the status code and raw text before parsing.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.