# pydoc > json

---
type: CommandReference
command: json
mode: pydoc
section: ""
source: pydoc3
---

## Quick Reference

- `json.dumps(obj)` — serialize Python object to JSON string
- `json.dump(obj, fp)` — serialize and write to file-like object
- `json.loads(s)` — deserialize JSON string to Python object
- `json.load(fp)` — deserialize from file-like object
- `json.dumps(obj, indent=4, sort_keys=True)` — pretty-print JSON
- `json.dumps(obj, separators=(',', ':'))` — compact encoding
- `python -m json.tool < file.json` — validate and pretty-print JSON from shell
- `json.JSONEncoder(default=func).encode(obj)` — custom serialization

## Name

JSON encoder and decoder for Python (Python 3.10 module).

## Functions

- `dump(obj, fp, *, 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` as JSON to a `.write()`-supporting file-like object `fp`.
- `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`.
- `load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)` — Deserialize JSON document from `fp` (a `.read()`-supporting file-like object) to a Python object.
- `loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)` — Deserialize JSON string `s` (str, bytes, or bytearray) to a Python object.

## Classes

- `JSONDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)` — JSON decoder. Default translation: JSON object -> dict, array -> list, string -> str, number (int) -> int, number (real) -> float, true -> True, false -> False, null -> None. Also understands NaN, Infinity, -Infinity.
  - `decode(s)` — Return Python representation of string `s`.
  - `raw_decode(s, idx=0)` — Decode JSON document from `s` and return (Python object, index where document ended).
- `JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)` — Extensible JSON encoder. Default translation: dict -> object, list/tuple -> array, str -> string, int/float -> number, True -> true, False -> false, None -> null.
  - `default(o)` — Override in subclass to serialize otherwise unsupported types; should return a JSON encodable object or raise TypeError.
  - `encode(o)` — Return JSON string representation of Python object `o`.
  - `iterencode(o, _one_shot=False)` — Encode object and yield each string chunk.
- `JSONDecodeError(msg, doc, pos)` — Subclass of ValueError with attributes: `msg` (unformatted error message), `doc` (parsed document), `pos` (start index of failure), `lineno`, `colno`.

## Options

Common parameters for `dump`, `dumps`, `load`, `loads` and/or class constructors:

- `skipkeys` (default `False`) — If `True`, skip non-basic dict keys (str, int, float, bool, None) instead of raising TypeError.
- `ensure_ascii` (default `True`) — If `True`, escape non-ASCII characters; if `False`, may include non-ASCII in output.
- `check_circular` (default `True`) — If `True`, check for circular references to prevent RecursionError.
- `allow_nan` (default `True`) — If `True`, encode NaN, Infinity, -Infinity as JavaScript equivalents; if `False`, raise ValueError.
- `sort_keys` (default `False`) — If `True`, output dictionaries sorted by key.
- `indent` (default `None`) — Non-negative integer for pretty-print indentation; `None` for compact.
- `separators` (default `(', ', ': ')` if indent is None, else `(',', ': ')`) — Tuple `(item_separator, key_separator)`. Use `(',', ':')` for most compact.
- `default` (default `None`) — Function called for objects that cannot be serialized; should return a JSON encodable object or raise TypeError.
- `object_hook` (default `None`) — Function called with result of every JSON object decoded (dict); return value replaces dict.
- `object_pairs_hook` (default `None`) — Like `object_hook` but receives ordered list of pairs; takes priority over `object_hook`.
- `parse_float` (default `None`) — Function called with string of every JSON float; default `float`.
- `parse_int` (default `None`) — Function called with string of every JSON int; default `int`.
- `parse_constant` (default `None`) — Function called with `-Infinity`, `Infinity`, `NaN` strings; can raise exception.
- `strict` (default `True`) — If `False`, allow control characters (0-31) in strings.
- `cls` (default `None`) — Custom JSONEncoder/JSONDecoder subclass to use.

## Examples

### Basic encoding and decoding

python
>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
['foo', {'bar': ['baz', None, 1.0, 2]}]
### Streaming with file-like objects

python
>>> from io import StringIO
>>> io = StringIO()
>>> json.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'
>>> io = StringIO('["streaming API"]')
>>> json.load(io)[0]
'streaming API'
### Pretty printing and compact encoding

python
>>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
{
    "4": 5,
    "6": 7
}
>>> json.dumps([1,2,3,{'4':5, '6':7}], separators=(',', ':'))
'[1,2,3,{"4":5,"6":7}]'
### Custom object decoding

python
>>> def as_complex(dct):
...     if '__complex__' in dct:
...         return complex(dct['real'], dct['imag'])
...     return dct
>>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', object_hook=as_complex)
(1+2j)
### Custom object encoding

python
>>> def encode_complex(obj):
...     if isinstance(obj, complex):
...         return [obj.real, obj.imag]
...     raise TypeError
>>> json.dumps(2 + 1j, default=encode_complex)
'[2.0, 1.0]'
### Shell usage with json.tool

shell
$ echo '{"json":"obj"}' | python -m json.tool
{
    "json": "obj"
}
## See Also

- Python module reference: [json](https://docs.python.org/3.10/library/json.html)
- External simplejson library: [simplejson](https://github.com/simplejson/simplejson)
- JSON specification: [json.org](https://json.org)