blob: 433f948ed8cd7ffe07e95e05e78d543516bc2d2a [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
Ezio Melottid654ded2012-11-29 00:35:29 +020045 >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True,
46 ... indent=4, separators=(',', ': ')))
Christian Heimes90540002008-05-08 14:29:10 +000047 {
Georg Brandl48310cd2009-01-03 21:18:54 +000048 "4": 5,
Christian Heimes90540002008-05-08 14:29:10 +000049 "6": 7
50 }
51
52Decoding JSON::
Georg Brandl48310cd2009-01-03 21:18:54 +000053
Christian Heimes90540002008-05-08 14:29:10 +000054 >>> import json
55 >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
Benjamin Peterson2505bc62008-05-15 02:17:58 +000056 ['foo', {'bar': ['baz', None, 1.0, 2]}]
Christian Heimes90540002008-05-08 14:29:10 +000057 >>> json.loads('"\\"foo\\bar"')
Benjamin Peterson2505bc62008-05-15 02:17:58 +000058 '"foo\x08ar'
59 >>> from io import StringIO
Christian Heimes90540002008-05-08 14:29:10 +000060 >>> io = StringIO('["streaming API"]')
61 >>> json.load(io)
Benjamin Peterson2505bc62008-05-15 02:17:58 +000062 ['streaming API']
Christian Heimes90540002008-05-08 14:29:10 +000063
64Specializing JSON object decoding::
65
66 >>> import json
67 >>> def as_complex(dct):
68 ... if '__complex__' in dct:
69 ... return complex(dct['real'], dct['imag'])
70 ... return dct
Benjamin Peterson2505bc62008-05-15 02:17:58 +000071 ...
Christian Heimes90540002008-05-08 14:29:10 +000072 >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
73 ... object_hook=as_complex)
74 (1+2j)
75 >>> import decimal
76 >>> json.loads('1.1', parse_float=decimal.Decimal)
77 Decimal('1.1')
78
79Extending :class:`JSONEncoder`::
Georg Brandl48310cd2009-01-03 21:18:54 +000080
Christian Heimes90540002008-05-08 14:29:10 +000081 >>> import json
82 >>> class ComplexEncoder(json.JSONEncoder):
83 ... def default(self, obj):
84 ... if isinstance(obj, complex):
85 ... return [obj.real, obj.imag]
R David Murraydd246172013-03-17 21:52:35 -040086 ... # Let the base class default method raise the TypeError
Christian Heimes90540002008-05-08 14:29:10 +000087 ... return json.JSONEncoder.default(self, obj)
Benjamin Peterson2505bc62008-05-15 02:17:58 +000088 ...
Georg Brandl0bb73b82010-09-03 22:36:22 +000089 >>> json.dumps(2 + 1j, cls=ComplexEncoder)
Christian Heimes90540002008-05-08 14:29:10 +000090 '[2.0, 1.0]'
91 >>> ComplexEncoder().encode(2 + 1j)
92 '[2.0, 1.0]'
93 >>> list(ComplexEncoder().iterencode(2 + 1j))
Georg Brandl0bb73b82010-09-03 22:36:22 +000094 ['[2.0', ', 1.0', ']']
Georg Brandl48310cd2009-01-03 21:18:54 +000095
Christian Heimes90540002008-05-08 14:29:10 +000096
Ezio Melotti84e59aa2012-04-13 21:02:18 -060097.. highlight:: bash
Christian Heimes90540002008-05-08 14:29:10 +000098
99Using json.tool from the shell to validate and pretty-print::
Georg Brandl48310cd2009-01-03 21:18:54 +0000100
Christian Heimes90540002008-05-08 14:29:10 +0000101 $ echo '{"json":"obj"}' | python -mjson.tool
102 {
103 "json": "obj"
104 }
Ezio Melotti84e59aa2012-04-13 21:02:18 -0600105 $ echo '{1.2:3.4}' | python -mjson.tool
Serhiy Storchakac510a042013-02-21 20:19:16 +0200106 Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
Christian Heimes90540002008-05-08 14:29:10 +0000107
Ezio Melotti84e59aa2012-04-13 21:02:18 -0600108.. highlight:: python3
Christian Heimes90540002008-05-08 14:29:10 +0000109
Georg Brandl48310cd2009-01-03 21:18:54 +0000110.. note::
Christian Heimes90540002008-05-08 14:29:10 +0000111
Antoine Pitrou331624b2012-08-24 19:37:23 +0200112 JSON is a subset of `YAML <http://yaml.org/>`_ 1.2. The JSON produced by
113 this module's default settings (in particular, the default *separators*
114 value) is also a subset of YAML 1.0 and 1.1. This module can thus also be
115 used as a YAML serializer.
Christian Heimes90540002008-05-08 14:29:10 +0000116
117
118Basic Usage
119-----------
120
Andrew Svetlov2ec53be2012-10-28 14:10:30 +0200121.. function:: dump(obj, fp, skipkeys=False, ensure_ascii=True, \
122 check_circular=True, allow_nan=True, cls=None, \
123 indent=None, separators=None, default=None, \
124 sort_keys=False, **kw)
Christian Heimes90540002008-05-08 14:29:10 +0000125
126 Serialize *obj* as a JSON formatted stream to *fp* (a ``.write()``-supporting
Ezio Melotti6d2bc6e2013-03-29 03:59:29 +0200127 :term:`file-like object`) using this :ref:`conversion table
128 <py-to-json-table>`.
Christian Heimes90540002008-05-08 14:29:10 +0000129
130 If *skipkeys* is ``True`` (default: ``False``), then dict keys that are not
Antoine Pitrou00d650b2011-01-21 21:37:32 +0000131 of a basic type (:class:`str`, :class:`int`, :class:`float`, :class:`bool`,
132 ``None``) will be skipped instead of raising a :exc:`TypeError`.
Christian Heimes90540002008-05-08 14:29:10 +0000133
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000134 The :mod:`json` module always produces :class:`str` objects, not
135 :class:`bytes` objects. Therefore, ``fp.write()`` must support :class:`str`
136 input.
137
Éric Araujo6f7aa002012-01-16 10:09:20 +0100138 If *ensure_ascii* is ``True`` (the default), the output is guaranteed to
139 have all incoming non-ASCII characters escaped. If *ensure_ascii* is
140 ``False``, these characters will be output as-is.
141
Christian Heimes90540002008-05-08 14:29:10 +0000142 If *check_circular* is ``False`` (default: ``True``), then the circular
143 reference check for container types will be skipped and a circular reference
144 will result in an :exc:`OverflowError` (or worse).
145
146 If *allow_nan* is ``False`` (default: ``True``), then it will be a
147 :exc:`ValueError` to serialize out of range :class:`float` values (``nan``,
148 ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of
149 using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
150
Raymond Hettingerb643ef82010-10-31 08:00:16 +0000151 If *indent* is a non-negative integer or string, then JSON array elements and
152 object members will be pretty-printed with that indent level. An indent level
R David Murrayd5315482011-04-12 21:09:18 -0400153 of 0, negative, or ``""`` will only insert newlines. ``None`` (the default)
154 selects the most compact representation. Using a positive integer indent
Petri Lehtinen72c6eef2012-08-27 20:27:30 +0300155 indents that many spaces per level. If *indent* is a string (such as ``"\t"``),
R David Murrayd5315482011-04-12 21:09:18 -0400156 that string is used to indent each level.
Christian Heimes90540002008-05-08 14:29:10 +0000157
Petri Lehtinen72b14262012-08-28 07:08:44 +0300158 .. versionchanged:: 3.2
159 Allow strings for *indent* in addition to integers.
160
Ezio Melottid654ded2012-11-29 00:35:29 +0200161 .. note::
162
163 Since the default item separator is ``', '``, the output might include
164 trailing whitespace when *indent* is specified. You can use
165 ``separators=(',', ': ')`` to avoid this.
166
Christian Heimes90540002008-05-08 14:29:10 +0000167 If *separators* is an ``(item_separator, dict_separator)`` tuple, then it
168 will be used instead of the default ``(', ', ': ')`` separators. ``(',',
169 ':')`` is the most compact JSON representation.
170
Christian Heimes90540002008-05-08 14:29:10 +0000171 *default(obj)* is a function that should return a serializable version of
172 *obj* or raise :exc:`TypeError`. The default simply raises :exc:`TypeError`.
173
Andrew Svetlov2ec53be2012-10-28 14:10:30 +0200174 If *sort_keys* is ``True`` (default: ``False``), then the output of
175 dictionaries will be sorted by key.
176
Georg Brandl1f01deb2009-01-03 22:47:39 +0000177 To use a custom :class:`JSONEncoder` subclass (e.g. one that overrides the
Christian Heimes90540002008-05-08 14:29:10 +0000178 :meth:`default` method to serialize additional types), specify it with the
Georg Brandld4460aa2010-10-15 17:03:02 +0000179 *cls* kwarg; otherwise :class:`JSONEncoder` is used.
Christian Heimes90540002008-05-08 14:29:10 +0000180
181
Andrew Svetlov2ec53be2012-10-28 14:10:30 +0200182.. function:: dumps(obj, skipkeys=False, ensure_ascii=True, \
183 check_circular=True, allow_nan=True, cls=None, \
184 indent=None, separators=None, default=None, \
185 sort_keys=False, **kw)
Christian Heimes90540002008-05-08 14:29:10 +0000186
Ezio Melotti6d2bc6e2013-03-29 03:59:29 +0200187 Serialize *obj* to a JSON formatted :class:`str` using this :ref:`conversion
188 table <py-to-json-table>`. The arguments have the same meaning as in
189 :func:`dump`.
Christian Heimes90540002008-05-08 14:29:10 +0000190
Ezio Melotti60adf952011-04-15 07:37:00 +0300191 .. note::
192
Georg Brandl340d2692011-04-16 16:54:15 +0200193 Unlike :mod:`pickle` and :mod:`marshal`, JSON is not a framed protocol,
194 so trying to serialize multiple objects with repeated calls to
195 :func:`dump` using the same *fp* will result in an invalid JSON file.
196
Senthil Kumaranf2123d22012-03-17 00:40:34 -0700197 .. note::
198
199 Keys in key/value pairs of JSON are always of the type :class:`str`. When
200 a dictionary is converted into JSON, all the keys of the dictionary are
Terry Jan Reedy9cbcc2f2013-03-08 19:35:15 -0500201 coerced to strings. As a result of this, if a dictionary is converted
Senthil Kumaranf2123d22012-03-17 00:40:34 -0700202 into JSON and then back into a dictionary, the dictionary may not equal
203 the original one. That is, ``loads(dumps(x)) != x`` if x has non-string
204 keys.
Christian Heimes90540002008-05-08 14:29:10 +0000205
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000206.. 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 +0000207
Antoine Pitrou15251a92012-08-24 19:49:08 +0200208 Deserialize *fp* (a ``.read()``-supporting :term:`file-like object`
Ezio Melotti6d2bc6e2013-03-29 03:59:29 +0200209 containing a JSON document) to a Python object using this :ref:`conversion
210 table <json-to-py-table>`.
Christian Heimes90540002008-05-08 14:29:10 +0000211
Christian Heimes90540002008-05-08 14:29:10 +0000212 *object_hook* is an optional function that will be called with the result of
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000213 any object literal decoded (a :class:`dict`). The return value of
Christian Heimes90540002008-05-08 14:29:10 +0000214 *object_hook* will be used instead of the :class:`dict`. This feature can be used
Antoine Pitrou331624b2012-08-24 19:37:23 +0200215 to implement custom decoders (e.g. `JSON-RPC <http://www.jsonrpc.org>`_
216 class hinting).
Christian Heimes90540002008-05-08 14:29:10 +0000217
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000218 *object_pairs_hook* is an optional function that will be called with the
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000219 result of any object literal decoded with an ordered list of pairs. The
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000220 return value of *object_pairs_hook* will be used instead of the
221 :class:`dict`. This feature can be used to implement custom decoders that
222 rely on the order that the key and value pairs are decoded (for example,
223 :func:`collections.OrderedDict` will remember the order of insertion). If
224 *object_hook* is also defined, the *object_pairs_hook* takes priority.
225
226 .. versionchanged:: 3.1
Hirokazu Yamamotoae9eb5c2009-04-26 03:34:06 +0000227 Added support for *object_pairs_hook*.
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000228
Christian Heimes90540002008-05-08 14:29:10 +0000229 *parse_float*, if specified, will be called with the string of every JSON
230 float to be decoded. By default, this is equivalent to ``float(num_str)``.
231 This can be used to use another datatype or parser for JSON floats
232 (e.g. :class:`decimal.Decimal`).
233
234 *parse_int*, if specified, will be called with the string of every JSON int
235 to be decoded. By default, this is equivalent to ``int(num_str)``. This can
236 be used to use another datatype or parser for JSON integers
237 (e.g. :class:`float`).
238
239 *parse_constant*, if specified, will be called with one of the following
Hynek Schlawack9729fd42012-05-16 19:01:04 +0200240 strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``.
241 This can be used to raise an exception if invalid JSON numbers
Christian Heimes90540002008-05-08 14:29:10 +0000242 are encountered.
243
Hynek Schlawackf54c0602012-05-20 18:32:53 +0200244 .. versionchanged:: 3.1
Hynek Schlawack1203e832012-05-20 12:03:17 +0200245 *parse_constant* doesn't get called on 'null', 'true', 'false' anymore.
246
Christian Heimes90540002008-05-08 14:29:10 +0000247 To use a custom :class:`JSONDecoder` subclass, specify it with the ``cls``
Georg Brandld4460aa2010-10-15 17:03:02 +0000248 kwarg; otherwise :class:`JSONDecoder` is used. Additional keyword arguments
249 will be passed to the constructor of the class.
Christian Heimes90540002008-05-08 14:29:10 +0000250
251
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000252.. 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 +0000253
Antoine Pitrou00d650b2011-01-21 21:37:32 +0000254 Deserialize *s* (a :class:`str` instance containing a JSON document) to a
Ezio Melotti6d2bc6e2013-03-29 03:59:29 +0200255 Python object using this :ref:`conversion table <json-to-py-table>`.
Christian Heimes90540002008-05-08 14:29:10 +0000256
Antoine Pitrou00d650b2011-01-21 21:37:32 +0000257 The other arguments have the same meaning as in :func:`load`, except
258 *encoding* which is ignored and deprecated.
Christian Heimes90540002008-05-08 14:29:10 +0000259
260
Antoine Pitrou331624b2012-08-24 19:37:23 +0200261Encoders and Decoders
Christian Heimes90540002008-05-08 14:29:10 +0000262---------------------
263
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000264.. 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 +0000265
266 Simple JSON decoder.
267
268 Performs the following translations in decoding by default:
269
Ezio Melotti6d2bc6e2013-03-29 03:59:29 +0200270 .. _json-to-py-table:
271
Christian Heimes90540002008-05-08 14:29:10 +0000272 +---------------+-------------------+
273 | JSON | Python |
274 +===============+===================+
275 | object | dict |
276 +---------------+-------------------+
277 | array | list |
278 +---------------+-------------------+
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000279 | string | str |
Christian Heimes90540002008-05-08 14:29:10 +0000280 +---------------+-------------------+
Georg Brandl639ce962009-04-11 18:18:16 +0000281 | number (int) | int |
Christian Heimes90540002008-05-08 14:29:10 +0000282 +---------------+-------------------+
283 | number (real) | float |
284 +---------------+-------------------+
285 | true | True |
286 +---------------+-------------------+
287 | false | False |
288 +---------------+-------------------+
289 | null | None |
290 +---------------+-------------------+
291
292 It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their
293 corresponding ``float`` values, which is outside the JSON spec.
294
Christian Heimes90540002008-05-08 14:29:10 +0000295 *object_hook*, if specified, will be called with the result of every JSON
296 object decoded and its return value will be used in place of the given
297 :class:`dict`. This can be used to provide custom deserializations (e.g. to
298 support JSON-RPC class hinting).
299
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000300 *object_pairs_hook*, if specified will be called with the result of every
301 JSON object decoded with an ordered list of pairs. The return value of
302 *object_pairs_hook* will be used instead of the :class:`dict`. This
303 feature can be used to implement custom decoders that rely on the order
304 that the key and value pairs are decoded (for example,
305 :func:`collections.OrderedDict` will remember the order of insertion). If
306 *object_hook* is also defined, the *object_pairs_hook* takes priority.
307
308 .. versionchanged:: 3.1
Hirokazu Yamamotoae9eb5c2009-04-26 03:34:06 +0000309 Added support for *object_pairs_hook*.
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000310
Christian Heimes90540002008-05-08 14:29:10 +0000311 *parse_float*, if specified, will be called with the string of every JSON
312 float to be decoded. By default, this is equivalent to ``float(num_str)``.
313 This can be used to use another datatype or parser for JSON floats
314 (e.g. :class:`decimal.Decimal`).
315
316 *parse_int*, if specified, will be called with the string of every JSON int
317 to be decoded. By default, this is equivalent to ``int(num_str)``. This can
318 be used to use another datatype or parser for JSON integers
319 (e.g. :class:`float`).
320
321 *parse_constant*, if specified, will be called with one of the following
322 strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``, ``'null'``, ``'true'``,
323 ``'false'``. This can be used to raise an exception if invalid JSON numbers
324 are encountered.
325
Georg Brandld4460aa2010-10-15 17:03:02 +0000326 If *strict* is ``False`` (``True`` is the default), then control characters
327 will be allowed inside strings. Control characters in this context are
328 those with character codes in the 0-31 range, including ``'\t'`` (tab),
329 ``'\n'``, ``'\r'`` and ``'\0'``.
330
Christian Heimes90540002008-05-08 14:29:10 +0000331
332 .. method:: decode(s)
333
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000334 Return the Python representation of *s* (a :class:`str` instance
335 containing a JSON document)
Christian Heimes90540002008-05-08 14:29:10 +0000336
337 .. method:: raw_decode(s)
338
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000339 Decode a JSON document from *s* (a :class:`str` beginning with a
340 JSON document) and return a 2-tuple of the Python representation
341 and the index in *s* where the document ended.
Christian Heimes90540002008-05-08 14:29:10 +0000342
343 This can be used to decode a JSON document from a string that may have
344 extraneous data at the end.
345
346
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000347.. 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 +0000348
349 Extensible JSON encoder for Python data structures.
350
351 Supports the following objects and types by default:
352
Ezio Melotti6d2bc6e2013-03-29 03:59:29 +0200353 .. _py-to-json-table:
354
Christian Heimes90540002008-05-08 14:29:10 +0000355 +-------------------+---------------+
356 | Python | JSON |
357 +===================+===============+
358 | dict | object |
359 +-------------------+---------------+
360 | list, tuple | array |
361 +-------------------+---------------+
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000362 | str | string |
Christian Heimes90540002008-05-08 14:29:10 +0000363 +-------------------+---------------+
Georg Brandl639ce962009-04-11 18:18:16 +0000364 | int, float | number |
Christian Heimes90540002008-05-08 14:29:10 +0000365 +-------------------+---------------+
366 | True | true |
367 +-------------------+---------------+
368 | False | false |
369 +-------------------+---------------+
370 | None | null |
371 +-------------------+---------------+
372
373 To extend this to recognize other objects, subclass and implement a
374 :meth:`default` method with another method that returns a serializable object
375 for ``o`` if possible, otherwise it should call the superclass implementation
376 (to raise :exc:`TypeError`).
377
378 If *skipkeys* is ``False`` (the default), then it is a :exc:`TypeError` to
Georg Brandl639ce962009-04-11 18:18:16 +0000379 attempt encoding of keys that are not str, int, float or None. If
Christian Heimes90540002008-05-08 14:29:10 +0000380 *skipkeys* is ``True``, such items are simply skipped.
381
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000382 If *ensure_ascii* is ``True`` (the default), the output is guaranteed to
383 have all incoming non-ASCII characters escaped. If *ensure_ascii* is
384 ``False``, these characters will be output as-is.
Christian Heimes90540002008-05-08 14:29:10 +0000385
386 If *check_circular* is ``True`` (the default), then lists, dicts, and custom
387 encoded objects will be checked for circular references during encoding to
388 prevent an infinite recursion (which would cause an :exc:`OverflowError`).
389 Otherwise, no such check takes place.
390
391 If *allow_nan* is ``True`` (the default), then ``NaN``, ``Infinity``, and
392 ``-Infinity`` will be encoded as such. This behavior is not JSON
393 specification compliant, but is consistent with most JavaScript based
394 encoders and decoders. Otherwise, it will be a :exc:`ValueError` to encode
395 such floats.
396
Georg Brandl6a74da32010-08-22 20:23:38 +0000397 If *sort_keys* is ``True`` (default ``False``), then the output of dictionaries
Christian Heimes90540002008-05-08 14:29:10 +0000398 will be sorted by key; this is useful for regression tests to ensure that
399 JSON serializations can be compared on a day-to-day basis.
400
Petri Lehtinen72b14262012-08-28 07:08:44 +0300401 If *indent* is a non-negative integer or string, then JSON array elements and
402 object members will be pretty-printed with that indent level. An indent level
403 of 0, negative, or ``""`` will only insert newlines. ``None`` (the default)
404 selects the most compact representation. Using a positive integer indent
405 indents that many spaces per level. If *indent* is a string (such as ``"\t"``),
406 that string is used to indent each level.
407
408 .. versionchanged:: 3.2
409 Allow strings for *indent* in addition to integers.
Christian Heimes90540002008-05-08 14:29:10 +0000410
Ezio Melottid654ded2012-11-29 00:35:29 +0200411 .. note::
412
413 Since the default item separator is ``', '``, the output might include
414 trailing whitespace when *indent* is specified. You can use
415 ``separators=(',', ': ')`` to avoid this.
416
Christian Heimes90540002008-05-08 14:29:10 +0000417 If specified, *separators* should be an ``(item_separator, key_separator)``
418 tuple. The default is ``(', ', ': ')``. To get the most compact JSON
419 representation, you should specify ``(',', ':')`` to eliminate whitespace.
420
421 If specified, *default* is a function that gets called for objects that can't
422 otherwise be serialized. It should return a JSON encodable version of the
423 object or raise a :exc:`TypeError`.
424
Christian Heimes90540002008-05-08 14:29:10 +0000425
426 .. method:: default(o)
427
428 Implement this method in a subclass such that it returns a serializable
429 object for *o*, or calls the base implementation (to raise a
430 :exc:`TypeError`).
431
432 For example, to support arbitrary iterators, you could implement default
433 like this::
Georg Brandl48310cd2009-01-03 21:18:54 +0000434
Christian Heimes90540002008-05-08 14:29:10 +0000435 def default(self, o):
436 try:
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +0000437 iterable = iter(o)
Christian Heimes90540002008-05-08 14:29:10 +0000438 except TypeError:
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +0000439 pass
Christian Heimes90540002008-05-08 14:29:10 +0000440 else:
441 return list(iterable)
R David Murraydd246172013-03-17 21:52:35 -0400442 # Let the base class default method raise the TypeError
Georg Brandl0bb73b82010-09-03 22:36:22 +0000443 return json.JSONEncoder.default(self, o)
Christian Heimes90540002008-05-08 14:29:10 +0000444
445
446 .. method:: encode(o)
447
448 Return a JSON string representation of a Python data structure, *o*. For
449 example::
450
Georg Brandl0bb73b82010-09-03 22:36:22 +0000451 >>> json.JSONEncoder().encode({"foo": ["bar", "baz"]})
Christian Heimes90540002008-05-08 14:29:10 +0000452 '{"foo": ["bar", "baz"]}'
453
454
455 .. method:: iterencode(o)
456
457 Encode the given object, *o*, and yield each string representation as
458 available. For example::
Georg Brandl48310cd2009-01-03 21:18:54 +0000459
Georg Brandl0bb73b82010-09-03 22:36:22 +0000460 for chunk in json.JSONEncoder().iterencode(bigobject):
Christian Heimes90540002008-05-08 14:29:10 +0000461 mysocket.write(chunk)
Antoine Pitrou331624b2012-08-24 19:37:23 +0200462
463
464Standard Compliance
465-------------------
466
467The JSON format is specified by :rfc:`4627`. This section details this
468module's level of compliance with the RFC. For simplicity,
469:class:`JSONEncoder` and :class:`JSONDecoder` subclasses, and parameters other
470than those explicitly mentioned, are not considered.
471
472This module does not comply with the RFC in a strict fashion, implementing some
473extensions that are valid JavaScript but not valid JSON. In particular:
474
475- Top-level non-object, non-array values are accepted and output;
476- Infinite and NaN number values are accepted and output;
477- Repeated names within an object are accepted, and only the value of the last
478 name-value pair is used.
479
480Since the RFC permits RFC-compliant parsers to accept input texts that are not
481RFC-compliant, this module's deserializer is technically RFC-compliant under
482default settings.
483
484Character Encodings
485^^^^^^^^^^^^^^^^^^^
486
487The RFC recommends that JSON be represented using either UTF-8, UTF-16, or
488UTF-32, with UTF-8 being the default.
489
490As permitted, though not required, by the RFC, this module's serializer sets
491*ensure_ascii=True* by default, thus escaping the output so that the resulting
492strings only contain ASCII characters.
493
494Other than the *ensure_ascii* parameter, this module is defined strictly in
495terms of conversion between Python objects and
496:class:`Unicode strings <str>`, and thus does not otherwise address the issue
497of character encodings.
498
499
500Top-level Non-Object, Non-Array Values
501^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
502
503The RFC specifies that the top-level value of a JSON text must be either a
504JSON object or array (Python :class:`dict` or :class:`list`). This module's
505deserializer also accepts input texts consisting solely of a
506JSON null, boolean, number, or string value::
507
508 >>> just_a_json_string = '"spam and eggs"' # Not by itself a valid JSON text
509 >>> json.loads(just_a_json_string)
510 'spam and eggs'
511
512This module itself does not include a way to request that such input texts be
513regarded as illegal. Likewise, this module's serializer also accepts single
514Python :data:`None`, :class:`bool`, numeric, and :class:`str`
515values as input and will generate output texts consisting solely of a top-level
516JSON null, boolean, number, or string value without raising an exception::
517
518 >>> neither_a_list_nor_a_dict = "spam and eggs"
519 >>> json.dumps(neither_a_list_nor_a_dict) # The result is not a valid JSON text
520 '"spam and eggs"'
521
522This module's serializer does not itself include a way to enforce the
523aforementioned constraint.
524
525
526Infinite and NaN Number Values
527^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
528
529The RFC does not permit the representation of infinite or NaN number values.
530Despite that, by default, this module accepts and outputs ``Infinity``,
531``-Infinity``, and ``NaN`` as if they were valid JSON number literal values::
532
533 >>> # Neither of these calls raises an exception, but the results are not valid JSON
534 >>> json.dumps(float('-inf'))
535 '-Infinity'
536 >>> json.dumps(float('nan'))
537 'NaN'
538 >>> # Same when deserializing
539 >>> json.loads('-Infinity')
540 -inf
541 >>> json.loads('NaN')
542 nan
543
544In the serializer, the *allow_nan* parameter can be used to alter this
545behavior. In the deserializer, the *parse_constant* parameter can be used to
546alter this behavior.
547
548
549Repeated Names Within an Object
550^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
551
552The RFC specifies that the names within a JSON object should be unique, but
553does not specify how repeated names in JSON objects should be handled. By
554default, this module does not raise an exception; instead, it ignores all but
555the last name-value pair for a given name::
556
557 >>> weird_json = '{"x": 1, "x": 2, "x": 3}'
558 >>> json.loads(weird_json)
559 {'x': 3}
560
561The *object_pairs_hook* parameter can be used to alter this behavior.