json — JSON encoder and decoder

Python json.dumps, json.loads, and their file counterparts, including the arguments and errors that belong to each function.

The json module is part of the Python standard library. It is not a built-in, and it is not a third-party package. Import it with `import json`.

dumps and dump serialize Python objects to JSON. loads and load parse JSON into Python objects. Sorting keys, indentation, and ensure_ascii belong to the encoder. object_hook and parse_float belong to the decoder. Do not look for sort_keys on loads, and do not expect dumps to raise JSONDecodeError.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

json.dumps and json.dump

json.dumps(obj) returns a JSON string. json.dump(obj, fp) writes that string to a file-like object. The keyword arguments below are shared by both functions and are keyword-only after the required positional arguments.

json.dumps

json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

Serialize obj to a JSON formatted str. The default encoder supports dict, list, tuple, str, int, float, bool, and None.

ParameterDescription
objThe Python object to encode.
ensure_asciiIf True (the default), non-ASCII characters are escaped as \uXXXX.
sort_keysIf True, object keys are sorted in the output. This argument exists only on the encoder.
indentIf a non-negative integer, pretty-print with that many spaces of indentation. None selects the most compact representation.
separatorsA (item_separator, key_separator) tuple. The compact default is (", ", ": "); (",", ":") removes extra spaces.
defaultA function called for objects the encoder does not support. If it cannot convert the object, it should raise TypeError.
allow_nanIf True (the default), NaN, Infinity, and -Infinity are encoded as non-standard JSON tokens. If False, those values raise ValueError.
skipkeysIf True, skip dict keys that are not basic types instead of raising TypeError.
check_circularIf True (the default), a circular reference raises ValueError instead of overflowing the stack.

Returns: A str containing JSON text. json.dump() writes to fp and returns None.

Raises

  • TypeError — Raised for unsupported types such as set, or for a dict key that is not a basic type when skipkeys is False.
  • ValueError — Raised for circular references when check_circular is True, and for out-of-range floats when allow_nan is False. This is not JSONDecodeError.
  • Dict keys are coerced to strings in the output. json.dumps({1: "x"}) returns '{"1": "x"}'. sort_keys=True still compares the original key objects, so mixing int and str keys raises TypeError.
  • datetime, bytes, and set values are not JSON-serializable unless you supply default= or a custom encoder class.
python
import json
import math

print(json.dumps({"city": "München"}))
print(json.dumps({"city": "München"}, ensure_ascii=False))
print(json.dumps({1: "x"}))
print(json.dumps({"b": 2, "a": 1}, sort_keys=True, separators=(",", ":")))
try:
    json.dumps({"port": math.nan}, allow_nan=False)
except ValueError as exc:
    print(type(exc).__name__)
try:
    json.dumps({"tags": {"alpha", "beta"}})
except TypeError as exc:
    print(type(exc).__name__)

Expected output

{"city": "M\u00fcnchen"}
{"city": "München"}
{"1": "x"}
{"a":1,"b":2}
ValueError
TypeError

Related: JSON Diff tool, json.loads, Normalize JSON before a text diff

Official documentation →

json.loads and json.load

json.loads(s) parses a JSON string. json.load(fp) reads from a file-like object. These functions do not accept sort_keys, indent, ensure_ascii, or default. Those options belong to the encoder.

json.loads

json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

Deserialize a JSON document to a Python object. Objects become dicts, arrays become lists, and JSON null becomes None.

ParameterDescription
sA str, bytes, or bytearray containing a JSON document.
object_hookIf given, a function called with each decoded object (a dict); its return value is used instead of the dict.
object_pairs_hookLike object_hook, but receives an ordered list of (key, value) pairs. Useful when you need to inspect duplicate keys before they are collapsed.
parse_floatIf given, called with every JSON float string instead of producing a float.
parse_intIf given, called with every JSON integer string instead of producing an int.
parse_constantIf given, called with "-Infinity", "Infinity", or "NaN" instead of producing those non-standard values.

Returns: The corresponding Python object.

Raises

  • json.JSONDecodeError — Raised for invalid JSON. This is a subclass of ValueError and includes msg, doc, pos, lineno, and colno. dumps() does not raise this exception.
  • The default decoder keeps the last value when an object contains duplicate keys.
  • By default, the decoder accepts NaN, Infinity, and -Infinity, which are not valid standard JSON.
python
import json

print(json.loads('{"port": 80, "host": null}'))
print(json.loads('{"a": 1, "a": 2}'))
print(json.loads("NaN"))
try:
    json.loads("{port: 80}")
except json.JSONDecodeError as exc:
    print(type(exc).__name__, isinstance(exc, ValueError), exc.msg)

Expected output

{'port': 80, 'host': None}
{'a': 2}
nan
JSONDecodeError True Expecting property name enclosed in double quotes

Related: json.dumps

Official documentation →

Normalize JSON before a text diff

Parse the JSON, then serialize it with sorted object keys and consistent separators. This removes formatting differences while preserving array order. This section keeps the original Python reference anchor.

Stable JSON text

json.dumps(json.loads(text), sort_keys=True, separators=(",", ":"), ensure_ascii=False)

A compact, key-sorted encoding is useful before comparing two JSON documents as text.

  • Array order is preserved. Only object keys are sorted.
  • The default decoder still collapses duplicate keys before you can serialize the result.
python
import json

data = json.loads('{"port": 80, "host": "localhost"}')
print(json.dumps(data, sort_keys=True, separators=(",", ":"), ensure_ascii=False))

Expected output

{"host":"localhost","port":80}

Official documentation →