1 :mod:`json` --- JSON encoder and decoder
2 ========================================
5 :synopsis: Encode and decode the JSON format.
6 .. moduleauthor:: Bob Ippolito <bob@redivi.com>
7 .. sectionauthor:: Bob Ippolito <bob@redivi.com>
10 `JSON (JavaScript Object Notation) <http://json.org>`_ is a subset of JavaScript
11 syntax (ECMA-262 3rd edition) used as a lightweight data interchange format.
13 :mod:`json` exposes an API familiar to users of the standard library
14 :mod:`marshal` and :mod:`pickle` modules.
16 Encoding basic Python object hierarchies::
19 >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
20 '["foo", {"bar": ["baz", null, 1.0, 2]}]'
21 >>> print json.dumps("\"foo\bar")
23 >>> print json.dumps(u'\u1234')
25 >>> print json.dumps('\\')
27 >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
28 {"a": 0, "b": 0, "c": 0}
29 >>> from StringIO import StringIO
31 >>> json.dump(['streaming API'], io)
38 >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
39 '[1,2,3,{"4":5,"6":7}]'
44 >>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
53 >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
54 [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
55 >>> json.loads('"\\"foo\\bar"')
57 >>> from StringIO import StringIO
58 >>> io = StringIO('["streaming API"]')
62 Specializing JSON object decoding::
65 >>> def as_complex(dct):
66 ... if '__complex__' in dct:
67 ... return complex(dct['real'], dct['imag'])
70 >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
71 ... object_hook=as_complex)
74 >>> json.loads('1.1', parse_float=decimal.Decimal)
77 Extending :class:`JSONEncoder`::
80 >>> class ComplexEncoder(json.JSONEncoder):
81 ... def default(self, obj):
82 ... if isinstance(obj, complex):
83 ... return [obj.real, obj.imag]
84 ... return json.JSONEncoder.default(self, obj)
86 >>> dumps(2 + 1j, cls=ComplexEncoder)
88 >>> ComplexEncoder().encode(2 + 1j)
90 >>> list(ComplexEncoder().iterencode(2 + 1j))
91 ['[', '2.0', ', ', '1.0', ']']
96 Using json.tool from the shell to validate and pretty-print::
98 $ echo '{"json":"obj"}' | python -mjson.tool
102 $ echo '{ 1.2:3.4}' | python -mjson.tool
103 Expecting property name: line 1 column 2 (char 2)
105 .. highlight:: python
109 The JSON produced by this module's default settings is a subset of
110 YAML, so it may be used as a serializer for that as well.
116 .. function:: dump(obj, fp[, skipkeys[, ensure_ascii[, check_circular[, allow_nan[, cls[, indent[, separators[, encoding[, default[, **kw]]]]]]]]]])
118 Serialize *obj* as a JSON formatted stream to *fp* (a ``.write()``-supporting
121 If *skipkeys* is ``True`` (default: ``False``), then dict keys that are not
122 of a basic type (:class:`str`, :class:`unicode`, :class:`int`, :class:`long`,
123 :class:`float`, :class:`bool`, ``None``) will be skipped instead of raising a
126 If *ensure_ascii* is ``False`` (default: ``True``), then some chunks written
127 to *fp* may be :class:`unicode` instances, subject to normal Python
128 :class:`str` to :class:`unicode` coercion rules. Unless ``fp.write()``
129 explicitly understands :class:`unicode` (as in :func:`codecs.getwriter`) this
130 is likely to cause an error.
132 If *check_circular* is ``False`` (default: ``True``), then the circular
133 reference check for container types will be skipped and a circular reference
134 will result in an :exc:`OverflowError` (or worse).
136 If *allow_nan* is ``False`` (default: ``True``), then it will be a
137 :exc:`ValueError` to serialize out of range :class:`float` values (``nan``,
138 ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of
139 using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
141 If *indent* is a non-negative integer, then JSON array elements and object
142 members will be pretty-printed with that indent level. An indent level of 0,
143 or negative, will only insert newlines. ``None`` (the default) selects the
144 most compact representation.
146 If *separators* is an ``(item_separator, dict_separator)`` tuple, then it
147 will be used instead of the default ``(', ', ': ')`` separators. ``(',',
148 ':')`` is the most compact JSON representation.
150 *encoding* is the character encoding for str instances, default is UTF-8.
152 *default(obj)* is a function that should return a serializable version of
153 *obj* or raise :exc:`TypeError`. The default simply raises :exc:`TypeError`.
155 To use a custom :class:`JSONEncoder` subclass (e.g. one that overrides the
156 :meth:`default` method to serialize additional types), specify it with the
157 *cls* kwarg; otherwise :class:`JSONEncoder` is used.
161 Unlike :mod:`pickle` and :mod:`marshal`, JSON is not a framed protocol so
162 trying to serialize more objects with repeated calls to :func:`dump` and
163 the same *fp* will result in an invalid JSON file.
165 .. function:: dumps(obj[, skipkeys[, ensure_ascii[, check_circular[, allow_nan[, cls[, indent[, separators[, encoding[, default[, **kw]]]]]]]]]])
167 Serialize *obj* to a JSON formatted :class:`str`.
169 If *ensure_ascii* is ``False``, then the return value will be a
170 :class:`unicode` instance. The other arguments have the same meaning as in
174 .. function:: load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
176 Deserialize *fp* (a ``.read()``-supporting file-like object containing a JSON
177 document) to a Python object.
179 If the contents of *fp* are encoded with an ASCII based encoding other than
180 UTF-8 (e.g. latin-1), then an appropriate *encoding* name must be specified.
181 Encodings that are not ASCII based (such as UCS-2) are not allowed, and
182 should be wrapped with ``codecs.getreader(encoding)(fp)``, or simply decoded
183 to a :class:`unicode` object and passed to :func:`loads`.
185 *object_hook* is an optional function that will be called with the result of
186 any object literal decoded (a :class:`dict`). The return value of
187 *object_hook* will be used instead of the :class:`dict`. This feature can be used
188 to implement custom decoders (e.g. JSON-RPC class hinting).
190 *object_pairs_hook* is an optional function that will be called with the
191 result of any object literal decoded with an ordered list of pairs. The
192 return value of *object_pairs_hook* will be used instead of the
193 :class:`dict`. This feature can be used to implement custom decoders that
194 rely on the order that the key and value pairs are decoded (for example,
195 :func:`collections.OrderedDict` will remember the order of insertion). If
196 *object_hook* is also defined, the *object_pairs_hook* takes priority.
198 .. versionchanged:: 2.7
199 Added support for *object_pairs_hook*.
201 *parse_float*, if specified, will be called with the string of every JSON
202 float to be decoded. By default, this is equivalent to ``float(num_str)``.
203 This can be used to use another datatype or parser for JSON floats
204 (e.g. :class:`decimal.Decimal`).
206 *parse_int*, if specified, will be called with the string of every JSON int
207 to be decoded. By default, this is equivalent to ``int(num_str)``. This can
208 be used to use another datatype or parser for JSON integers
209 (e.g. :class:`float`).
211 *parse_constant*, if specified, will be called with one of the following
212 strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``, ``'null'``, ``'true'``,
213 ``'false'``. This can be used to raise an exception if invalid JSON numbers
216 To use a custom :class:`JSONDecoder` subclass, specify it with the ``cls``
217 kwarg; otherwise :class:`JSONDecoder` is used. Additional keyword arguments
218 will be passed to the constructor of the class.
221 .. function:: loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
223 Deserialize *s* (a :class:`str` or :class:`unicode` instance containing a JSON
224 document) to a Python object.
226 If *s* is a :class:`str` instance and is encoded with an ASCII based encoding
227 other than UTF-8 (e.g. latin-1), then an appropriate *encoding* name must be
228 specified. Encodings that are not ASCII based (such as UCS-2) are not
229 allowed and should be decoded to :class:`unicode` first.
231 The other arguments have the same meaning as in :func:`load`.
234 Encoders and decoders
235 ---------------------
237 .. class:: JSONDecoder([encoding[, object_hook[, parse_float[, parse_int[, parse_constant[, strict[, object_pairs_hook]]]]]]])
241 Performs the following translations in decoding by default:
243 +---------------+-------------------+
245 +===============+===================+
247 +---------------+-------------------+
249 +---------------+-------------------+
251 +---------------+-------------------+
252 | number (int) | int, long |
253 +---------------+-------------------+
254 | number (real) | float |
255 +---------------+-------------------+
257 +---------------+-------------------+
259 +---------------+-------------------+
261 +---------------+-------------------+
263 It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their
264 corresponding ``float`` values, which is outside the JSON spec.
266 *encoding* determines the encoding used to interpret any :class:`str` objects
267 decoded by this instance (UTF-8 by default). It has no effect when decoding
268 :class:`unicode` objects.
270 Note that currently only encodings that are a superset of ASCII work, strings
271 of other encodings should be passed in as :class:`unicode`.
273 *object_hook*, if specified, will be called with the result of every JSON
274 object decoded and its return value will be used in place of the given
275 :class:`dict`. This can be used to provide custom deserializations (e.g. to
276 support JSON-RPC class hinting).
278 *object_pairs_hook*, if specified will be called with the result of every
279 JSON object decoded with an ordered list of pairs. The return value of
280 *object_pairs_hook* will be used instead of the :class:`dict`. This
281 feature can be used to implement custom decoders that rely on the order
282 that the key and value pairs are decoded (for example,
283 :func:`collections.OrderedDict` will remember the order of insertion). If
284 *object_hook* is also defined, the *object_pairs_hook* takes priority.
286 .. versionchanged:: 2.7
287 Added support for *object_pairs_hook*.
289 *parse_float*, if specified, will be called with the string of every JSON
290 float to be decoded. By default, this is equivalent to ``float(num_str)``.
291 This can be used to use another datatype or parser for JSON floats
292 (e.g. :class:`decimal.Decimal`).
294 *parse_int*, if specified, will be called with the string of every JSON int
295 to be decoded. By default, this is equivalent to ``int(num_str)``. This can
296 be used to use another datatype or parser for JSON integers
297 (e.g. :class:`float`).
299 *parse_constant*, if specified, will be called with one of the following
300 strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``, ``'null'``, ``'true'``,
301 ``'false'``. This can be used to raise an exception if invalid JSON numbers
304 If *strict* is ``False`` (``True`` is the default), then control characters
305 will be allowed inside strings. Control characters in this context are
306 those with character codes in the 0-31 range, including ``'\t'`` (tab),
307 ``'\n'``, ``'\r'`` and ``'\0'``.
310 .. method:: decode(s)
312 Return the Python representation of *s* (a :class:`str` or
313 :class:`unicode` instance containing a JSON document)
315 .. method:: raw_decode(s)
317 Decode a JSON document from *s* (a :class:`str` or :class:`unicode`
318 beginning with a JSON document) and return a 2-tuple of the Python
319 representation and the index in *s* where the document ended.
321 This can be used to decode a JSON document from a string that may have
322 extraneous data at the end.
325 .. class:: JSONEncoder([skipkeys[, ensure_ascii[, check_circular[, allow_nan[, sort_keys[, indent[, separators[, encoding[, default]]]]]]]]])
327 Extensible JSON encoder for Python data structures.
329 Supports the following objects and types by default:
331 +-------------------+---------------+
333 +===================+===============+
335 +-------------------+---------------+
336 | list, tuple | array |
337 +-------------------+---------------+
338 | str, unicode | string |
339 +-------------------+---------------+
340 | int, long, float | number |
341 +-------------------+---------------+
343 +-------------------+---------------+
345 +-------------------+---------------+
347 +-------------------+---------------+
349 To extend this to recognize other objects, subclass and implement a
350 :meth:`default` method with another method that returns a serializable object
351 for ``o`` if possible, otherwise it should call the superclass implementation
352 (to raise :exc:`TypeError`).
354 If *skipkeys* is ``False`` (the default), then it is a :exc:`TypeError` to
355 attempt encoding of keys that are not str, int, long, float or None. If
356 *skipkeys* is ``True``, such items are simply skipped.
358 If *ensure_ascii* is ``True`` (the default), the output is guaranteed to be
359 :class:`str` objects with all incoming unicode characters escaped. If
360 *ensure_ascii* is ``False``, the output will be a unicode object.
362 If *check_circular* is ``True`` (the default), then lists, dicts, and custom
363 encoded objects will be checked for circular references during encoding to
364 prevent an infinite recursion (which would cause an :exc:`OverflowError`).
365 Otherwise, no such check takes place.
367 If *allow_nan* is ``True`` (the default), then ``NaN``, ``Infinity``, and
368 ``-Infinity`` will be encoded as such. This behavior is not JSON
369 specification compliant, but is consistent with most JavaScript based
370 encoders and decoders. Otherwise, it will be a :exc:`ValueError` to encode
373 If *sort_keys* is ``True`` (default ``False``), then the output of dictionaries
374 will be sorted by key; this is useful for regression tests to ensure that
375 JSON serializations can be compared on a day-to-day basis.
377 If *indent* is a non-negative integer (it is ``None`` by default), then JSON
378 array elements and object members will be pretty-printed with that indent
379 level. An indent level of 0 will only insert newlines. ``None`` is the most
380 compact representation.
382 If specified, *separators* should be an ``(item_separator, key_separator)``
383 tuple. The default is ``(', ', ': ')``. To get the most compact JSON
384 representation, you should specify ``(',', ':')`` to eliminate whitespace.
386 If specified, *default* is a function that gets called for objects that can't
387 otherwise be serialized. It should return a JSON encodable version of the
388 object or raise a :exc:`TypeError`.
390 If *encoding* is not ``None``, then all input strings will be transformed
391 into unicode using that encoding prior to JSON-encoding. The default is
395 .. method:: default(o)
397 Implement this method in a subclass such that it returns a serializable
398 object for *o*, or calls the base implementation (to raise a
401 For example, to support arbitrary iterators, you could implement default
404 def default(self, o):
410 return list(iterable)
411 return JSONEncoder.default(self, o)
414 .. method:: encode(o)
416 Return a JSON string representation of a Python data structure, *o*. For
419 >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
420 '{"foo": ["bar", "baz"]}'
423 .. method:: iterencode(o)
425 Encode the given object, *o*, and yield each string representation as
426 available. For example::
428 for chunk in JSONEncoder().iterencode(bigobject):
429 mysocket.write(chunk)