Python Reference ยท Files, Paths and Text I/O
The json module
Reference for Python's json module: encode objects to JSON text, decode JSON into dicts and lists, indent and sort output, custom types, and common errors.
The json module converts between Python objects and JSON text, the format most web APIs and configuration files use. Four functions do almost all the work: dumps() and loads() work with strings, while dump() and load() work with file objects.
JSON has fewer types than Python, so the round trip is not always lossless. Dictionaries become objects, lists and tuples become arrays, and keys always become strings. Types such as set, datetime and Decimal are not supported out of the box; you teach the encoder about them with the default argument.
import json text = json.dumps({"name": "Ada", "langs": ["Python", "C"]}) data = json.loads(text)
Try it
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.
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.
Main functions
| Function | What it does |
|---|---|
json.dumps(obj, **options) |
Returns a JSON str. |
json.dump(obj, fp, **options) |
Writes JSON text to a text file object. Returns None. |
json.loads(s, **options) |
Parses a str (or bytes/bytearray in UTF-8, UTF-16 or UTF-32) and returns Python objects. |
json.load(fp, **options) |
Reads all of a file object and parses it. |
json.JSONDecodeError |
Subclass of ValueError raised for invalid JSON. Has msg, doc, pos, lineno and colno. |
json.JSONEncoder, json.JSONDecoder |
The classes behind the functions; subclass them or pass them as cls=. |
Common options for dumps() and dump()
| Option | Effect |
|---|---|
indent |
A number of spaces (or a string such as "\t") for pretty printing. None gives the compact one-line form. |
sort_keys |
Sort object keys alphabetically, which makes output stable and diff-friendly. |
separators |
An (item_separator, key_separator) pair. (",", ":") gives the most compact output. |
ensure_ascii |
When True (default), non-ASCII characters are written as \uXXXX escapes. Set False to keep them readable. |
default |
A function called for objects the encoder cannot serialize. It should return a serializable value or raise TypeError. |
allow_nan |
When True (default), NaN and Infinity are written, which is not valid standard JSON. Set False to raise ValueError instead. |
Common options for loads() and load()
| Option | Effect |
|---|---|
object_hook |
Called with every decoded object (dict); its return value replaces the dict. Use it to build your own classes. |
object_pairs_hook |
Like object_hook but receives a list of key/value pairs, in order. |
parse_float, parse_int |
Functions used for numbers, for example parse_float=Decimal to avoid binary rounding. |
Usage notes
- Type mapping.
dictis object,listandtupleare array,stris string,intandfloatare number,True/False/Nonearetrue/false/null. Decoding always returnsdict,list,str,int,float,boolandNone. - Tuples come back as lists and non-string keys come back as strings, so
loads(dumps(x)) == xis not guaranteed. Integer keys become"1". - Keys must be strings, numbers, booleans or
None. Other key types raiseTypeError; thedefaulthook is not consulted for keys. dumpandloadneed file objects, not paths. Open the file first (usually withencoding="utf-8"), or usepathlib.Path.read_text()withloads().- Do not mix up
loadandloads. The trailingsstands for string. Passing a string toload()fails with anAttributeErrorbecause it tries to call.read(). - Duplicate keys in the input are accepted; the last one wins.
- JSON is not a safe place for sensitive Python objects. Unlike
pickle, decoding JSON never runs code, so it is safe for untrusted input, though large inputs can still use a lot of memory. - Streams of many records. The module has no streaming parser. For huge data, use the JSON Lines format (one object per line) and call
loads()per line. - Python 3.14 can also be run as
python -m json, a small command line pretty printer (python -m json.toolstill works).
Related
pickle,csv,pprint,ValueError- Lessons: JSON in Python, Files, Dictionaries