blob: 5d97ee88fc49ceb0deee9717f8210f0c140d0dcc [file] [log] [blame]
Christian Heimes90540002008-05-08 14:29:10 +00001:mod:`json` --- JSON encoder and decoder
2========================================
3
4.. module:: json
5 :synopsis: Encode and decode the JSON format.
6.. moduleauthor:: Bob Ippolito <bob@redivi.com>
7.. sectionauthor:: Bob Ippolito <bob@redivi.com>
Christian Heimes90540002008-05-08 14:29:10 +00008
Antoine Pitrou331624b2012-08-24 19:37:23 +02009`JSON (JavaScript Object Notation) <http://json.org>`_, specified by
10:rfc:`4627`, is a lightweight data interchange format based on a subset of
11`JavaScript <http://en.wikipedia.org/wiki/JavaScript>`_ syntax (`ECMA-262 3rd
12edition <http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf>`_).
Christian Heimes90540002008-05-08 14:29:10 +000013
14:mod:`json` exposes an API familiar to users of the standard library
15:mod:`marshal` and :mod:`pickle` modules.
16
17Encoding basic Python object hierarchies::
Georg Brandl48310cd2009-01-03 21:18:54 +000018
Christian Heimes90540002008-05-08 14:29:10 +000019 >>> import json
20 >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
21 '["foo", {"bar": ["baz", null, 1.0, 2]}]'
Neal Norwitz752abd02008-05-13 04:55:24 +000022 >>> print(json.dumps("\"foo\bar"))
Christian Heimes90540002008-05-08 14:29:10 +000023 "\"foo\bar"
Benjamin Peterson2505bc62008-05-15 02:17:58 +000024 >>> print(json.dumps('\u1234'))
Christian Heimes90540002008-05-08 14:29:10 +000025 "\u1234"
Neal Norwitz752abd02008-05-13 04:55:24 +000026 >>> print(json.dumps('\\'))
Christian Heimes90540002008-05-08 14:29:10 +000027 "\\"
Neal Norwitz752abd02008-05-13 04:55:24 +000028 >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
Christian Heimes90540002008-05-08 14:29:10 +000029 {"a": 0, "b": 0, "c": 0}
Benjamin Peterson2505bc62008-05-15 02:17:58 +000030 >>> from io import StringIO
Christian Heimes90540002008-05-08 14:29:10 +000031 >>> io = StringIO()
32 >>> json.dump(['streaming API'], io)
33 >>> io.getvalue()
34 '["streaming API"]'
35
36Compact encoding::
37
38 >>> import json
Éric Araujode579d42011-04-21 02:37:41 +020039 >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',', ':'))
Christian Heimes90540002008-05-08 14:29:10 +000040 '[1,2,3,{"4":5,"6":7}]'
41
42Pretty printing::
43
44 >>> import json
Neal Norwitz752abd02008-05-13 04:55:24 +000045 >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
Christian Heimes90540002008-05-08 14:29:10 +000046 {
Georg Brandl48310cd2009-01-03 21:18:54 +000047 "4": 5,
Christian Heimes90540002008-05-08 14:29:10 +000048 "6": 7
49 }
50
51Decoding JSON::
Georg Brandl48310cd2009-01-03 21:18:54 +000052
Christian Heimes90540002008-05-08 14:29:10 +000053 >>> import json
54 >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
Benjamin Peterson2505bc62008-05-15 02:17:58 +000055 ['foo', {'bar': ['baz', None, 1.0, 2]}]
Christian Heimes90540002008-05-08 14:29:10 +000056 >>> json.loads('"\\"foo\\bar"')
Benjamin Peterson2505bc62008-05-15 02:17:58 +000057 '"foo\x08ar'
58 >>> from io import StringIO
Christian Heimes90540002008-05-08 14:29:10 +000059 >>> io = StringIO('["streaming API"]')
60 >>> json.load(io)
Benjamin Peterson2505bc62008-05-15 02:17:58 +000061 ['streaming API']
Christian Heimes90540002008-05-08 14:29:10 +000062
63Specializing JSON object decoding::
64
65 >>> import json
66 >>> def as_complex(dct):
67 ... if '__complex__' in dct:
68 ... return complex(dct['real'], dct['imag'])
69 ... return dct
Benjamin Peterson2505bc62008-05-15 02:17:58 +000070 ...
Christian Heimes90540002008-05-08 14:29:10 +000071 >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
72 ... object_hook=as_complex)
73 (1+2j)
74 >>> import decimal
75 >>> json.loads('1.1', parse_float=decimal.Decimal)
76 Decimal('1.1')
77
78Extending :class:`JSONEncoder`::
Georg Brandl48310cd2009-01-03 21:18:54 +000079
Christian Heimes90540002008-05-08 14:29:10 +000080 >>> import json
81 >>> class ComplexEncoder(json.JSONEncoder):
82 ... def default(self, obj):
83 ... if isinstance(obj, complex):
84 ... return [obj.real, obj.imag]
R David Murraydd246172013-03-17 21:52:35 -040085 ... # Let the base class default method raise the TypeError
Christian Heimes90540002008-05-08 14:29:10 +000086 ... return json.JSONEncoder.default(self, obj)
Benjamin Peterson2505bc62008-05-15 02:17:58 +000087 ...
Georg Brandl0bb73b82010-09-03 22:36:22 +000088 >>> json.dumps(2 + 1j, cls=ComplexEncoder)
Christian Heimes90540002008-05-08 14:29:10 +000089 '[2.0, 1.0]'
90 >>> ComplexEncoder().encode(2 + 1j)
91 '[2.0, 1.0]'
92 >>> list(ComplexEncoder().iterencode(2 + 1j))
Georg Brandl0bb73b82010-09-03 22:36:22 +000093 ['[2.0', ', 1.0', ']']
Georg Brandl48310cd2009-01-03 21:18:54 +000094
Christian Heimes90540002008-05-08 14:29:10 +000095
Ezio Melotti84e59aa2012-04-13 21:02:18 -060096.. highlight:: bash
Christian Heimes90540002008-05-08 14:29:10 +000097
98Using json.tool from the shell to validate and pretty-print::
Georg Brandl48310cd2009-01-03 21:18:54 +000099
Christian Heimes90540002008-05-08 14:29:10 +0000100 $ echo '{"json":"obj"}' | python -mjson.tool
101 {
102 "json": "obj"
103 }
Ezio Melotti84e59aa2012-04-13 21:02:18 -0600104 $ echo '{1.2:3.4}' | python -mjson.tool
Serhiy Storchakac510a042013-02-21 20:19:16 +0200105 Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
Christian Heimes90540002008-05-08 14:29:10 +0000106
Ezio Melotti84e59aa2012-04-13 21:02:18 -0600107.. highlight:: python3
Christian Heimes90540002008-05-08 14:29:10 +0000108
Georg Brandl48310cd2009-01-03 21:18:54 +0000109.. note::
Christian Heimes90540002008-05-08 14:29:10 +0000110
Antoine Pitrou331624b2012-08-24 19:37:23 +0200111 JSON is a subset of `YAML <http://yaml.org/>`_ 1.2. The JSON produced by
112 this module's default settings (in particular, the default *separators*
113 value) is also a subset of YAML 1.0 and 1.1. This module can thus also be
114 used as a YAML serializer.
Christian Heimes90540002008-05-08 14:29:10 +0000115
116
117Basic Usage
118-----------
119
Andrew Svetlov2ec53be2012-10-28 14:10:30 +0200120.. function:: dump(obj, fp, skipkeys=False, ensure_ascii=True, \
121 check_circular=True, allow_nan=True, cls=None, \
122 indent=None, separators=None, default=None, \
123 sort_keys=False, **kw)
Christian Heimes90540002008-05-08 14:29:10 +0000124
125 Serialize *obj* as a JSON formatted stream to *fp* (a ``.write()``-supporting
Ezio Melotti6d2bc6e2013-03-29 03:59:29 +0200126 :term:`file-like object`) using this :ref:`conversion table
127 <py-to-json-table>`.
Christian Heimes90540002008-05-08 14:29:10 +0000128
129 If *skipkeys* is ``True`` (default: ``False``), then dict keys that are not
Antoine Pitrou00d650b2011-01-21 21:37:32 +0000130 of a basic type (:class:`str`, :class:`int`, :class:`float`, :class:`bool`,
131 ``None``) will be skipped instead of raising a :exc:`TypeError`.
Christian Heimes90540002008-05-08 14:29:10 +0000132
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000133 The :mod:`json` module always produces :class:`str` objects, not
134 :class:`bytes` objects. Therefore, ``fp.write()`` must support :class:`str`
135 input.
136
Éric Araujo6f7aa002012-01-16 10:09:20 +0100137 If *ensure_ascii* is ``True`` (the default), the output is guaranteed to
138 have all incoming non-ASCII characters escaped. If *ensure_ascii* is
139 ``False``, these characters will be output as-is.
140
Christian Heimes90540002008-05-08 14:29:10 +0000141 If *check_circular* is ``False`` (default: ``True``), then the circular
142 reference check for container types will be skipped and a circular reference
143 will result in an :exc:`OverflowError` (or worse).
144
145 If *allow_nan* is ``False`` (default: ``True``), then it will be a
146 :exc:`ValueError` to serialize out of range :class:`float` values (``nan``,
147 ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of
148 using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
149
Raymond Hettingerb643ef82010-10-31 08:00:16 +0000150 If *indent* is a non-negative integer or string, then JSON array elements and
151 object members will be pretty-printed with that indent level. An indent level
R David Murrayd5315482011-04-12 21:09:18 -0400152 of 0, negative, or ``""`` will only insert newlines. ``None`` (the default)
153 selects the most compact representation. Using a positive integer indent
Petri Lehtinen72c6eef2012-08-27 20:27:30 +0300154 indents that many spaces per level. If *indent* is a string (such as ``"\t"``),
R David Murrayd5315482011-04-12 21:09:18 -0400155 that string is used to indent each level.
Christian Heimes90540002008-05-08 14:29:10 +0000156
Petri Lehtinen72b14262012-08-28 07:08:44 +0300157 .. versionchanged:: 3.2
158 Allow strings for *indent* in addition to integers.
159
Ezio Melotti10031442012-11-29 00:42:56 +0200160 If specified, *separators* should be an ``(item_separator, key_separator)``
161 tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and
162 ``(',', ': ')`` otherwise. To get the most compact JSON representation,
163 you should specify ``(',', ':')`` to eliminate whitespace.
164
165 .. versionchanged:: 3.4
166 Use ``(',', ': ')`` as default if *indent* is not ``None``.
Christian Heimes90540002008-05-08 14:29:10 +0000167
Christian Heimes90540002008-05-08 14:29:10 +0000168 *default(obj)* is a function that should return a serializable version of
169 *obj* or raise :exc:`TypeError`. The default simply raises :exc:`TypeError`.
170
Andrew Svetlov2ec53be2012-10-28 14:10:30 +0200171 If *sort_keys* is ``True`` (default: ``False``), then the output of
172 dictionaries will be sorted by key.
173
Georg Brandl1f01deb2009-01-03 22:47:39 +0000174 To use a custom :class:`JSONEncoder` subclass (e.g. one that overrides the
Christian Heimes90540002008-05-08 14:29:10 +0000175 :meth:`default` method to serialize additional types), specify it with the
Georg Brandld4460aa2010-10-15 17:03:02 +0000176 *cls* kwarg; otherwise :class:`JSONEncoder` is used.
Christian Heimes90540002008-05-08 14:29:10 +0000177
178
Andrew Svetlov2ec53be2012-10-28 14:10:30 +0200179.. function:: dumps(obj, skipkeys=False, ensure_ascii=True, \
180 check_circular=True, allow_nan=True, cls=None, \
181 indent=None, separators=None, default=None, \
182 sort_keys=False, **kw)
Christian Heimes90540002008-05-08 14:29:10 +0000183
Ezio Melotti6d2bc6e2013-03-29 03:59:29 +0200184 Serialize *obj* to a JSON formatted :class:`str` using this :ref:`conversion
185 table <py-to-json-table>`. The arguments have the same meaning as in
186 :func:`dump`.
Christian Heimes90540002008-05-08 14:29:10 +0000187
Ezio Melotti60adf952011-04-15 07:37:00 +0300188 .. note::
189
Georg Brandl340d2692011-04-16 16:54:15 +0200190 Unlike :mod:`pickle` and :mod:`marshal`, JSON is not a framed protocol,
191 so trying to serialize multiple objects with repeated calls to
192 :func:`dump` using the same *fp* will result in an invalid JSON file.
193
Senthil Kumaranf2123d22012-03-17 00:40:34 -0700194 .. note::
195
196 Keys in key/value pairs of JSON are always of the type :class:`str`. When
197 a dictionary is converted into JSON, all the keys of the dictionary are
Terry Jan Reedy9cbcc2f2013-03-08 19:35:15 -0500198 coerced to strings. As a result of this, if a dictionary is converted
Senthil Kumaranf2123d22012-03-17 00:40:34 -0700199 into JSON and then back into a dictionary, the dictionary may not equal
200 the original one. That is, ``loads(dumps(x)) != x`` if x has non-string
201 keys.
Christian Heimes90540002008-05-08 14:29:10 +0000202
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000203.. function:: load(fp, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
Christian Heimes90540002008-05-08 14:29:10 +0000204
Antoine Pitrou15251a92012-08-24 19:49:08 +0200205 Deserialize *fp* (a ``.read()``-supporting :term:`file-like object`
Ezio Melotti6d2bc6e2013-03-29 03:59:29 +0200206 containing a JSON document) to a Python object using this :ref:`conversion
207 table <json-to-py-table>`.
Christian Heimes90540002008-05-08 14:29:10 +0000208
Christian Heimes90540002008-05-08 14:29:10 +0000209 *object_hook* is an optional function that will be called with the result of
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000210 any object literal decoded (a :class:`dict`). The return value of
Christian Heimes90540002008-05-08 14:29:10 +0000211 *object_hook* will be used instead of the :class:`dict`. This feature can be used
Antoine Pitrou331624b2012-08-24 19:37:23 +0200212 to implement custom decoders (e.g. `JSON-RPC <http://www.jsonrpc.org>`_
213 class hinting).
Christian Heimes90540002008-05-08 14:29:10 +0000214
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000215 *object_pairs_hook* is an optional function that will be called with the
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000216 result of any object literal decoded with an ordered list of pairs. The
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000217 return value of *object_pairs_hook* will be used instead of the
218 :class:`dict`. This feature can be used to implement custom decoders that
219 rely on the order that the key and value pairs are decoded (for example,
220 :func:`collections.OrderedDict` will remember the order of insertion). If
221 *object_hook* is also defined, the *object_pairs_hook* takes priority.
222
223 .. versionchanged:: 3.1
Hirokazu Yamamotoae9eb5c2009-04-26 03:34:06 +0000224 Added support for *object_pairs_hook*.
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000225
Christian Heimes90540002008-05-08 14:29:10 +0000226 *parse_float*, if specified, will be called with the string of every JSON
227 float to be decoded. By default, this is equivalent to ``float(num_str)``.
228 This can be used to use another datatype or parser for JSON floats
229 (e.g. :class:`decimal.Decimal`).
230
231 *parse_int*, if specified, will be called with the string of every JSON int
232 to be decoded. By default, this is equivalent to ``int(num_str)``. This can
233 be used to use another datatype or parser for JSON integers
234 (e.g. :class:`float`).
235
236 *parse_constant*, if specified, will be called with one of the following
Hynek Schlawack9729fd42012-05-16 19:01:04 +0200237 strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``.
238 This can be used to raise an exception if invalid JSON numbers
Christian Heimes90540002008-05-08 14:29:10 +0000239 are encountered.
240
Hynek Schlawackf54c0602012-05-20 18:32:53 +0200241 .. versionchanged:: 3.1
Hynek Schlawack1203e832012-05-20 12:03:17 +0200242 *parse_constant* doesn't get called on 'null', 'true', 'false' anymore.
243
Christian Heimes90540002008-05-08 14:29:10 +0000244 To use a custom :class:`JSONDecoder` subclass, specify it with the ``cls``
Georg Brandld4460aa2010-10-15 17:03:02 +0000245 kwarg; otherwise :class:`JSONDecoder` is used. Additional keyword arguments
246 will be passed to the constructor of the class.
Christian Heimes90540002008-05-08 14:29:10 +0000247
Felix Crux60fb9712013-08-12 17:39:51 -0400248 If the data being deserialized is not a valid JSON document, a
249 :exc:`ValueError` will be raised.
Christian Heimes90540002008-05-08 14:29:10 +0000250
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000251.. function:: loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
Christian Heimes90540002008-05-08 14:29:10 +0000252
Antoine Pitrou00d650b2011-01-21 21:37:32 +0000253 Deserialize *s* (a :class:`str` instance containing a JSON document) to a
Ezio Melotti6d2bc6e2013-03-29 03:59:29 +0200254 Python object using this :ref:`conversion table <json-to-py-table>`.
Christian Heimes90540002008-05-08 14:29:10 +0000255
Antoine Pitrou00d650b2011-01-21 21:37:32 +0000256 The other arguments have the same meaning as in :func:`load`, except
257 *encoding* which is ignored and deprecated.
Christian Heimes90540002008-05-08 14:29:10 +0000258
Felix Cruxb4357992013-08-12 17:39:51 -0400259 If the data being deserialized is not a valid JSON document, a
260 :exc:`ValueError` will be raised.
Christian Heimes90540002008-05-08 14:29:10 +0000261
Antoine Pitrou331624b2012-08-24 19:37:23 +0200262Encoders and Decoders
Christian Heimes90540002008-05-08 14:29:10 +0000263---------------------
264
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000265.. class:: JSONDecoder(object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)
Christian Heimes90540002008-05-08 14:29:10 +0000266
267 Simple JSON decoder.
268
269 Performs the following translations in decoding by default:
270
Ezio Melotti6d2bc6e2013-03-29 03:59:29 +0200271 .. _json-to-py-table:
272
Christian Heimes90540002008-05-08 14:29:10 +0000273 +---------------+-------------------+
274 | JSON | Python |
275 +===============+===================+
276 | object | dict |
277 +---------------+-------------------+
278 | array | list |
279 +---------------+-------------------+
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000280 | string | str |
Christian Heimes90540002008-05-08 14:29:10 +0000281 +---------------+-------------------+
Georg Brandl639ce962009-04-11 18:18:16 +0000282 | number (int) | int |
Christian Heimes90540002008-05-08 14:29:10 +0000283 +---------------+-------------------+
284 | number (real) | float |
285 +---------------+-------------------+
286 | true | True |
287 +---------------+-------------------+
288 | false | False |
289 +---------------+-------------------+
290 | null | None |
291 +---------------+-------------------+
292
293 It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their
294 corresponding ``float`` values, which is outside the JSON spec.
295
Christian Heimes90540002008-05-08 14:29:10 +0000296 *object_hook*, if specified, will be called with the result of every JSON
297 object decoded and its return value will be used in place of the given
298 :class:`dict`. This can be used to provide custom deserializations (e.g. to
299 support JSON-RPC class hinting).
300
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000301 *object_pairs_hook*, if specified will be called with the result of every
302 JSON object decoded with an ordered list of pairs. The return value of
303 *object_pairs_hook* will be used instead of the :class:`dict`. This
304 feature can be used to implement custom decoders that rely on the order
305 that the key and value pairs are decoded (for example,
306 :func:`collections.OrderedDict` will remember the order of insertion). If
307 *object_hook* is also defined, the *object_pairs_hook* takes priority.
308
309 .. versionchanged:: 3.1
Hirokazu Yamamotoae9eb5c2009-04-26 03:34:06 +0000310 Added support for *object_pairs_hook*.
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000311
Christian Heimes90540002008-05-08 14:29:10 +0000312 *parse_float*, if specified, will be called with the string of every JSON
313 float to be decoded. By default, this is equivalent to ``float(num_str)``.
314 This can be used to use another datatype or parser for JSON floats
315 (e.g. :class:`decimal.Decimal`).
316
317 *parse_int*, if specified, will be called with the string of every JSON int
318 to be decoded. By default, this is equivalent to ``int(num_str)``. This can
319 be used to use another datatype or parser for JSON integers
320 (e.g. :class:`float`).
321
322 *parse_constant*, if specified, will be called with one of the following
323 strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``, ``'null'``, ``'true'``,
324 ``'false'``. This can be used to raise an exception if invalid JSON numbers
325 are encountered.
326
Georg Brandld4460aa2010-10-15 17:03:02 +0000327 If *strict* is ``False`` (``True`` is the default), then control characters
328 will be allowed inside strings. Control characters in this context are
329 those with character codes in the 0-31 range, including ``'\t'`` (tab),
330 ``'\n'``, ``'\r'`` and ``'\0'``.
331
Felix Crux654f0032013-08-12 17:39:51 -0400332 If the data being deserialized is not a valid JSON document, a
333 :exc:`ValueError` will be raised.
Christian Heimes90540002008-05-08 14:29:10 +0000334
335 .. method:: decode(s)
336
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000337 Return the Python representation of *s* (a :class:`str` instance
338 containing a JSON document)
Christian Heimes90540002008-05-08 14:29:10 +0000339
340 .. method:: raw_decode(s)
341
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000342 Decode a JSON document from *s* (a :class:`str` beginning with a
343 JSON document) and return a 2-tuple of the Python representation
344 and the index in *s* where the document ended.
Christian Heimes90540002008-05-08 14:29:10 +0000345
346 This can be used to decode a JSON document from a string that may have
347 extraneous data at the end.
348
349
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000350.. class:: JSONEncoder(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)
Christian Heimes90540002008-05-08 14:29:10 +0000351
352 Extensible JSON encoder for Python data structures.
353
354 Supports the following objects and types by default:
355
Ezio Melotti6d2bc6e2013-03-29 03:59:29 +0200356 .. _py-to-json-table:
357
Ethan Furmana4998a72013-08-10 13:01:45 -0700358 +----------------------------------------+---------------+
359 | Python | JSON |
360 +========================================+===============+
361 | dict | object |
362 +----------------------------------------+---------------+
363 | list, tuple | array |
364 +----------------------------------------+---------------+
365 | str | string |
366 +----------------------------------------+---------------+
367 | int, float, int- & float-derived Enums | number |
368 +----------------------------------------+---------------+
369 | True | true |
370 +----------------------------------------+---------------+
371 | False | false |
372 +----------------------------------------+---------------+
373 | None | null |
374 +----------------------------------------+---------------+
375
376 .. versionchanged:: 3.4
377 Added support for int- and float-derived Enum classes.
Christian Heimes90540002008-05-08 14:29:10 +0000378
379 To extend this to recognize other objects, subclass and implement a
380 :meth:`default` method with another method that returns a serializable object
381 for ``o`` if possible, otherwise it should call the superclass implementation
382 (to raise :exc:`TypeError`).
383
384 If *skipkeys* is ``False`` (the default), then it is a :exc:`TypeError` to
Georg Brandl639ce962009-04-11 18:18:16 +0000385 attempt encoding of keys that are not str, int, float or None. If
Christian Heimes90540002008-05-08 14:29:10 +0000386 *skipkeys* is ``True``, such items are simply skipped.
387
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000388 If *ensure_ascii* is ``True`` (the default), the output is guaranteed to
389 have all incoming non-ASCII characters escaped. If *ensure_ascii* is
390 ``False``, these characters will be output as-is.
Christian Heimes90540002008-05-08 14:29:10 +0000391
392 If *check_circular* is ``True`` (the default), then lists, dicts, and custom
393 encoded objects will be checked for circular references during encoding to
394 prevent an infinite recursion (which would cause an :exc:`OverflowError`).
395 Otherwise, no such check takes place.
396
397 If *allow_nan* is ``True`` (the default), then ``NaN``, ``Infinity``, and
398 ``-Infinity`` will be encoded as such. This behavior is not JSON
399 specification compliant, but is consistent with most JavaScript based
400 encoders and decoders. Otherwise, it will be a :exc:`ValueError` to encode
401 such floats.
402
Georg Brandl6a74da32010-08-22 20:23:38 +0000403 If *sort_keys* is ``True`` (default ``False``), then the output of dictionaries
Christian Heimes90540002008-05-08 14:29:10 +0000404 will be sorted by key; this is useful for regression tests to ensure that
405 JSON serializations can be compared on a day-to-day basis.
406
Petri Lehtinen72b14262012-08-28 07:08:44 +0300407 If *indent* is a non-negative integer or string, then JSON array elements and
408 object members will be pretty-printed with that indent level. An indent level
409 of 0, negative, or ``""`` will only insert newlines. ``None`` (the default)
410 selects the most compact representation. Using a positive integer indent
411 indents that many spaces per level. If *indent* is a string (such as ``"\t"``),
412 that string is used to indent each level.
413
414 .. versionchanged:: 3.2
415 Allow strings for *indent* in addition to integers.
Christian Heimes90540002008-05-08 14:29:10 +0000416
417 If specified, *separators* should be an ``(item_separator, key_separator)``
Ezio Melotti10031442012-11-29 00:42:56 +0200418 tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and
419 ``(',', ': ')`` otherwise. To get the most compact JSON representation,
420 you should specify ``(',', ':')`` to eliminate whitespace.
421
422 .. versionchanged:: 3.4
423 Use ``(',', ': ')`` as default if *indent* is not ``None``.
Christian Heimes90540002008-05-08 14:29:10 +0000424
425 If specified, *default* is a function that gets called for objects that can't
426 otherwise be serialized. It should return a JSON encodable version of the
427 object or raise a :exc:`TypeError`.
428
Christian Heimes90540002008-05-08 14:29:10 +0000429
430 .. method:: default(o)
431
432 Implement this method in a subclass such that it returns a serializable
433 object for *o*, or calls the base implementation (to raise a
434 :exc:`TypeError`).
435
436 For example, to support arbitrary iterators, you could implement default
437 like this::
Georg Brandl48310cd2009-01-03 21:18:54 +0000438
Christian Heimes90540002008-05-08 14:29:10 +0000439 def default(self, o):
440 try:
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +0000441 iterable = iter(o)
Christian Heimes90540002008-05-08 14:29:10 +0000442 except TypeError:
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +0000443 pass
Christian Heimes90540002008-05-08 14:29:10 +0000444 else:
445 return list(iterable)
R David Murraydd246172013-03-17 21:52:35 -0400446 # Let the base class default method raise the TypeError
Georg Brandl0bb73b82010-09-03 22:36:22 +0000447 return json.JSONEncoder.default(self, o)
Christian Heimes90540002008-05-08 14:29:10 +0000448
449
450 .. method:: encode(o)
451
452 Return a JSON string representation of a Python data structure, *o*. For
453 example::
454
Georg Brandl0bb73b82010-09-03 22:36:22 +0000455 >>> json.JSONEncoder().encode({"foo": ["bar", "baz"]})
Christian Heimes90540002008-05-08 14:29:10 +0000456 '{"foo": ["bar", "baz"]}'
457
458
459 .. method:: iterencode(o)
460
461 Encode the given object, *o*, and yield each string representation as
462 available. For example::
Georg Brandl48310cd2009-01-03 21:18:54 +0000463
Georg Brandl0bb73b82010-09-03 22:36:22 +0000464 for chunk in json.JSONEncoder().iterencode(bigobject):
Christian Heimes90540002008-05-08 14:29:10 +0000465 mysocket.write(chunk)
Antoine Pitrou331624b2012-08-24 19:37:23 +0200466
467
468Standard Compliance
469-------------------
470
471The JSON format is specified by :rfc:`4627`. This section details this
472module's level of compliance with the RFC. For simplicity,
473:class:`JSONEncoder` and :class:`JSONDecoder` subclasses, and parameters other
474than those explicitly mentioned, are not considered.
475
476This module does not comply with the RFC in a strict fashion, implementing some
477extensions that are valid JavaScript but not valid JSON. In particular:
478
479- Top-level non-object, non-array values are accepted and output;
480- Infinite and NaN number values are accepted and output;
481- Repeated names within an object are accepted, and only the value of the last
482 name-value pair is used.
483
484Since the RFC permits RFC-compliant parsers to accept input texts that are not
485RFC-compliant, this module's deserializer is technically RFC-compliant under
486default settings.
487
488Character Encodings
489^^^^^^^^^^^^^^^^^^^
490
491The RFC recommends that JSON be represented using either UTF-8, UTF-16, or
492UTF-32, with UTF-8 being the default.
493
494As permitted, though not required, by the RFC, this module's serializer sets
495*ensure_ascii=True* by default, thus escaping the output so that the resulting
496strings only contain ASCII characters.
497
498Other than the *ensure_ascii* parameter, this module is defined strictly in
499terms of conversion between Python objects and
500:class:`Unicode strings <str>`, and thus does not otherwise address the issue
501of character encodings.
502
503
504Top-level Non-Object, Non-Array Values
505^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
506
507The RFC specifies that the top-level value of a JSON text must be either a
508JSON object or array (Python :class:`dict` or :class:`list`). This module's
509deserializer also accepts input texts consisting solely of a
510JSON null, boolean, number, or string value::
511
512 >>> just_a_json_string = '"spam and eggs"' # Not by itself a valid JSON text
513 >>> json.loads(just_a_json_string)
514 'spam and eggs'
515
516This module itself does not include a way to request that such input texts be
517regarded as illegal. Likewise, this module's serializer also accepts single
518Python :data:`None`, :class:`bool`, numeric, and :class:`str`
519values as input and will generate output texts consisting solely of a top-level
520JSON null, boolean, number, or string value without raising an exception::
521
522 >>> neither_a_list_nor_a_dict = "spam and eggs"
523 >>> json.dumps(neither_a_list_nor_a_dict) # The result is not a valid JSON text
524 '"spam and eggs"'
525
526This module's serializer does not itself include a way to enforce the
527aforementioned constraint.
528
529
530Infinite and NaN Number Values
531^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
532
533The RFC does not permit the representation of infinite or NaN number values.
534Despite that, by default, this module accepts and outputs ``Infinity``,
535``-Infinity``, and ``NaN`` as if they were valid JSON number literal values::
536
537 >>> # Neither of these calls raises an exception, but the results are not valid JSON
538 >>> json.dumps(float('-inf'))
539 '-Infinity'
540 >>> json.dumps(float('nan'))
541 'NaN'
542 >>> # Same when deserializing
543 >>> json.loads('-Infinity')
544 -inf
545 >>> json.loads('NaN')
546 nan
547
548In the serializer, the *allow_nan* parameter can be used to alter this
549behavior. In the deserializer, the *parse_constant* parameter can be used to
550alter this behavior.
551
552
553Repeated Names Within an Object
554^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
555
556The RFC specifies that the names within a JSON object should be unique, but
557does not specify how repeated names in JSON objects should be handled. By
558default, this module does not raise an exception; instead, it ignores all but
559the last name-value pair for a given name::
560
561 >>> weird_json = '{"x": 1, "x": 2, "x": 3}'
562 >>> json.loads(weird_json)
563 {'x': 3}
564
565The *object_pairs_hook* parameter can be used to alter this behavior.