The json module provides an API similar to pickle for
converting in-memory Python objects to a serialized representation
known as JavaScript Object Notation (JSON). Unlike pickle, JSON has
the benefit of having implementations in many languages (especially
JavaScript). It is most widely used for communicating between the web
server and client in a REST API, but is also useful for other
inter-application communication needs.

Another benefit of JSON over pickle is that the results are
human-readable. The dumps() function accepts several arguments
to make the output even nicer. For example, the sort_keys flag
tells the encoder to output the keys of a dictionary in sorted,
instead of random, order.

Verbose output like this increases the number of bytes needed to
transmit the same amount of data, however, so it is not intended for
use in a production environment. In fact, it is possible to adjust
the settings for separating data in the encoded output to make it even
more compact than the default.

The separators argument to dumps() should be a tuple
containing the strings to separate items in a list and keys from
values in a dictionary. The default is (',',':'). By removing
the whitespace, a more compact output is produced.

The JSON format expects the keys to a dictionary to be strings.
Trying to encode a dictionary with non-string types as keys produces a
TypeError. One way to work around that limitation is to tell
the encoder to skip over non-string keys using the skipkeys
argument:

In convert_to_builtin_type(), instances of classes not recognized
by json are converted to dictionaries with enough information
to re-create the object if a program has access to the Python modules
necessary.

To decode the results and create a MyObj() instance, use the
object_hook argument to loads() to tie in to the decoder so
the class can be imported from the module and used to create the
instance.

The object_hook is called for each dictionary decoded from the
incoming data stream, providing a chance to convert the dictionary to
another type of object. The hook function should return the object
the calling application should receive instead of the dictionary.

importjsonimportjson_myobjclassMyEncoder(json.JSONEncoder):defdefault(self,obj):print('default(',repr(obj),')')# Convert objects to a dictionary of their representationd={'__class__':obj.__class__.__name__,'__module__':obj.__module__,}d.update(obj.__dict__)returndobj=json_myobj.MyObj('internal data')print(obj)print(MyEncoder().encode(obj))

All of the examples so far have assumed that the encoded version of
the entire data structure could be held in memory at one time. With
large data structures, it may be preferable to write the encoding
directly to a file-like object. The convenience functions
load() and dump() accept references to a file-like object
to use for reading or writing.

JSONDecoder includes raw_decode(), a method for
decoding a data structure followed by more data, such as JSON data
with trailing text. The return value is the object created by
decoding the input data, and an index into that data indicating where
decoding left off.

The json.tool module implements a command line program for
reformatting JSON data to be easier to read.

[{"a":"A","c":3.0,"b":[2,4]}]

The input file example.json contains a mapping with the keys out
of alphabetical order. The first example below shows the data
reformatted in order, and the second example uses --sort-keys to
sort the mapping keys before printing the output.

Navigation

The output from all the example programs
from PyMOTW-3 has been generated with Python 3.5.2, unless
otherwise noted. Some of the features described here may not be
available in earlier versions of Python.