blob: ed5cf2165ac947581653c32bc13529c22c85826c [file] [log] [blame]
Georg Brandl3961f182008-05-05 20:53:39 +00001:mod:`json` --- JSON encoder and decoder
2========================================
Brett Cannon4b964f92008-05-05 20:21:38 +00003
4.. module:: json
Georg Brandl3961f182008-05-05 20:53:39 +00005 :synopsis: Encode and decode the JSON format.
Brett Cannon4b964f92008-05-05 20:21:38 +00006.. moduleauthor:: Bob Ippolito <bob@redivi.com>
7.. sectionauthor:: Bob Ippolito <bob@redivi.com>
8.. versionadded:: 2.6
9
Antoine Pitrouf3e0a692012-08-24 19:46:17 +020010`JSON (JavaScript Object Notation) <http://json.org>`_, specified by
11:rfc:`4627`, is a lightweight data interchange format based on a subset of
12`JavaScript <http://en.wikipedia.org/wiki/JavaScript>`_ syntax (`ECMA-262 3rd
13edition <http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf>`_).
Brett Cannon4b964f92008-05-05 20:21:38 +000014
Georg Brandl3961f182008-05-05 20:53:39 +000015:mod:`json` exposes an API familiar to users of the standard library
16:mod:`marshal` and :mod:`pickle` modules.
Brett Cannon4b964f92008-05-05 20:21:38 +000017
18Encoding basic Python object hierarchies::
Georg Brandlc62ef8b2009-01-03 20:55:06 +000019
Brett Cannon4b964f92008-05-05 20:21:38 +000020 >>> import json
21 >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
22 '["foo", {"bar": ["baz", null, 1.0, 2]}]'
23 >>> print json.dumps("\"foo\bar")
24 "\"foo\bar"
25 >>> print json.dumps(u'\u1234')
26 "\u1234"
27 >>> print json.dumps('\\')
28 "\\"
29 >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
30 {"a": 0, "b": 0, "c": 0}
31 >>> from StringIO import StringIO
32 >>> io = StringIO()
33 >>> json.dump(['streaming API'], io)
34 >>> io.getvalue()
35 '["streaming API"]'
36
37Compact encoding::
38
39 >>> import json
40 >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
41 '[1,2,3,{"4":5,"6":7}]'
42
43Pretty printing::
44
45 >>> import json
46 >>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
47 {
Georg Brandlc62ef8b2009-01-03 20:55:06 +000048 "4": 5,
Brett Cannon4b964f92008-05-05 20:21:38 +000049 "6": 7
50 }
51
52Decoding JSON::
Georg Brandlc62ef8b2009-01-03 20:55:06 +000053
Brett Cannon4b964f92008-05-05 20:21:38 +000054 >>> import json
55 >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
56 [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
57 >>> json.loads('"\\"foo\\bar"')
58 u'"foo\x08ar'
59 >>> from StringIO import StringIO
60 >>> io = StringIO('["streaming API"]')
61 >>> json.load(io)
62 [u'streaming API']
63
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
Georg Brandlc62ef8b2009-01-03 20:55:06 +000071 ...
Brett Cannon4b964f92008-05-05 20:21:38 +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
Georg Brandl3961f182008-05-05 20:53:39 +000079Extending :class:`JSONEncoder`::
Georg Brandlc62ef8b2009-01-03 20:55:06 +000080
Brett Cannon4b964f92008-05-05 20:21:38 +000081 >>> import json
82 >>> class ComplexEncoder(json.JSONEncoder):
83 ... def default(self, obj):
84 ... if isinstance(obj, complex):
85 ... return [obj.real, obj.imag]
86 ... return json.JSONEncoder.default(self, obj)
Georg Brandlc62ef8b2009-01-03 20:55:06 +000087 ...
Brett Cannon4b964f92008-05-05 20:21:38 +000088 >>> dumps(2 + 1j, cls=ComplexEncoder)
89 '[2.0, 1.0]'
90 >>> ComplexEncoder().encode(2 + 1j)
91 '[2.0, 1.0]'
92 >>> list(ComplexEncoder().iterencode(2 + 1j))
93 ['[', '2.0', ', ', '1.0', ']']
Georg Brandlc62ef8b2009-01-03 20:55:06 +000094
Brett Cannon4b964f92008-05-05 20:21:38 +000095
96.. highlight:: none
97
98Using json.tool from the shell to validate and pretty-print::
Georg Brandlc62ef8b2009-01-03 20:55:06 +000099
Brett Cannon4b964f92008-05-05 20:21:38 +0000100 $ echo '{"json":"obj"}' | python -mjson.tool
101 {
102 "json": "obj"
103 }
Antoine Pitroud9a51372012-06-29 01:58:26 +0200104 $ echo '{1.2:3.4}' | python -mjson.tool
105 Expecting property name enclosed in double quotes: line 1 column 1 (char 1)
Brett Cannon4b964f92008-05-05 20:21:38 +0000106
107.. highlight:: python
108
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000109.. note::
Brett Cannon4b964f92008-05-05 20:21:38 +0000110
Antoine Pitrouf3e0a692012-08-24 19:46:17 +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.
Brett Cannon4b964f92008-05-05 20:21:38 +0000115
116
117Basic Usage
118-----------
119
120.. function:: dump(obj, fp[, skipkeys[, ensure_ascii[, check_circular[, allow_nan[, cls[, indent[, separators[, encoding[, default[, **kw]]]]]]]]]])
121
Georg Brandl3961f182008-05-05 20:53:39 +0000122 Serialize *obj* as a JSON formatted stream to *fp* (a ``.write()``-supporting
Antoine Pitrou85ede8d2012-08-24 19:49:08 +0200123 :term:`file-like object`).
Brett Cannon4b964f92008-05-05 20:21:38 +0000124
Georg Brandl3961f182008-05-05 20:53:39 +0000125 If *skipkeys* is ``True`` (default: ``False``), then dict keys that are not
126 of a basic type (:class:`str`, :class:`unicode`, :class:`int`, :class:`long`,
127 :class:`float`, :class:`bool`, ``None``) will be skipped instead of raising a
128 :exc:`TypeError`.
Brett Cannon4b964f92008-05-05 20:21:38 +0000129
Petri Lehtinenf9e1f112012-09-01 07:27:58 +0300130 If *ensure_ascii* is ``True`` (the default), all non-ASCII characters in the
131 output are escaped with ``\uXXXX`` sequences, and the result is a
132 :class:`str` instance consisting of ASCII characters only. If
133 *ensure_ascii* is ``False``, some chunks written to *fp* may be
134 :class:`unicode` instances. This usually happens because the input contains
135 unicode strings or the *encoding* parameter is used. Unless ``fp.write()``
136 explicitly understands :class:`unicode` (as in :func:`codecs.getwriter`)
137 this is likely to cause an error.
Brett Cannon4b964f92008-05-05 20:21:38 +0000138
Georg Brandl3961f182008-05-05 20:53:39 +0000139 If *check_circular* is ``False`` (default: ``True``), then the circular
140 reference check for container types will be skipped and a circular reference
141 will result in an :exc:`OverflowError` (or worse).
Brett Cannon4b964f92008-05-05 20:21:38 +0000142
Georg Brandl3961f182008-05-05 20:53:39 +0000143 If *allow_nan* is ``False`` (default: ``True``), then it will be a
144 :exc:`ValueError` to serialize out of range :class:`float` values (``nan``,
145 ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of
146 using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
Brett Cannon4b964f92008-05-05 20:21:38 +0000147
Georg Brandl3961f182008-05-05 20:53:39 +0000148 If *indent* is a non-negative integer, then JSON array elements and object
R David Murrayea8b6ef2011-04-12 21:00:26 -0400149 members will be pretty-printed with that indent level. An indent level of 0,
150 or negative, will only insert newlines. ``None`` (the default) selects the
151 most compact representation.
Brett Cannon4b964f92008-05-05 20:21:38 +0000152
Georg Brandl3961f182008-05-05 20:53:39 +0000153 If *separators* is an ``(item_separator, dict_separator)`` tuple, then it
154 will be used instead of the default ``(', ', ': ')`` separators. ``(',',
155 ':')`` is the most compact JSON representation.
Brett Cannon4b964f92008-05-05 20:21:38 +0000156
Georg Brandl3961f182008-05-05 20:53:39 +0000157 *encoding* is the character encoding for str instances, default is UTF-8.
Brett Cannon4b964f92008-05-05 20:21:38 +0000158
Georg Brandl3961f182008-05-05 20:53:39 +0000159 *default(obj)* is a function that should return a serializable version of
160 *obj* or raise :exc:`TypeError`. The default simply raises :exc:`TypeError`.
Brett Cannon4b964f92008-05-05 20:21:38 +0000161
Georg Brandlfc29f272009-01-02 20:25:14 +0000162 To use a custom :class:`JSONEncoder` subclass (e.g. one that overrides the
Georg Brandl3961f182008-05-05 20:53:39 +0000163 :meth:`default` method to serialize additional types), specify it with the
Georg Brandldb949b82010-10-15 17:04:45 +0000164 *cls* kwarg; otherwise :class:`JSONEncoder` is used.
Brett Cannon4b964f92008-05-05 20:21:38 +0000165
Ezio Melotti6033d262011-04-15 07:37:00 +0300166 .. note::
167
168 Unlike :mod:`pickle` and :mod:`marshal`, JSON is not a framed protocol so
169 trying to serialize more objects with repeated calls to :func:`dump` and
170 the same *fp* will result in an invalid JSON file.
Brett Cannon4b964f92008-05-05 20:21:38 +0000171
Georg Brandl3961f182008-05-05 20:53:39 +0000172.. function:: dumps(obj[, skipkeys[, ensure_ascii[, check_circular[, allow_nan[, cls[, indent[, separators[, encoding[, default[, **kw]]]]]]]]]])
Brett Cannon4b964f92008-05-05 20:21:38 +0000173
Petri Lehtinenf9e1f112012-09-01 07:27:58 +0300174 Serialize *obj* to a JSON formatted :class:`str`. If *ensure_ascii* is
175 ``False``, the result may contain non-ASCII characters and the return value
176 may be a :class:`unicode` instance.
Brett Cannon4b964f92008-05-05 20:21:38 +0000177
Petri Lehtinenf9e1f112012-09-01 07:27:58 +0300178 The arguments have the same meaning as in :func:`dump`.
Brett Cannon4b964f92008-05-05 20:21:38 +0000179
Senthil Kumarane3d73542012-03-17 00:37:38 -0700180 .. note::
181
182 Keys in key/value pairs of JSON are always of the type :class:`str`. When
183 a dictionary is converted into JSON, all the keys of the dictionary are
184 coerced to strings. As a result of this, if a dictionary is convered
185 into JSON and then back into a dictionary, the dictionary may not equal
186 the original one. That is, ``loads(dumps(x)) != x`` if x has non-string
187 keys.
Brett Cannon4b964f92008-05-05 20:21:38 +0000188
Raymond Hettinger91852ca2009-03-19 19:19:03 +0000189.. function:: load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Brett Cannon4b964f92008-05-05 20:21:38 +0000190
Antoine Pitrou85ede8d2012-08-24 19:49:08 +0200191 Deserialize *fp* (a ``.read()``-supporting :term:`file-like object`
192 containing a JSON document) to a Python object.
Brett Cannon4b964f92008-05-05 20:21:38 +0000193
Georg Brandl3961f182008-05-05 20:53:39 +0000194 If the contents of *fp* are encoded with an ASCII based encoding other than
195 UTF-8 (e.g. latin-1), then an appropriate *encoding* name must be specified.
196 Encodings that are not ASCII based (such as UCS-2) are not allowed, and
Georg Brandl49cc4ea2009-04-23 08:44:57 +0000197 should be wrapped with ``codecs.getreader(encoding)(fp)``, or simply decoded
Georg Brandl3961f182008-05-05 20:53:39 +0000198 to a :class:`unicode` object and passed to :func:`loads`.
Brett Cannon4b964f92008-05-05 20:21:38 +0000199
200 *object_hook* is an optional function that will be called with the result of
Andrew M. Kuchling19672002009-03-30 22:29:15 +0000201 any object literal decoded (a :class:`dict`). The return value of
Georg Brandl3961f182008-05-05 20:53:39 +0000202 *object_hook* will be used instead of the :class:`dict`. This feature can be used
Antoine Pitrouf3e0a692012-08-24 19:46:17 +0200203 to implement custom decoders (e.g. `JSON-RPC <http://www.jsonrpc.org>`_
204 class hinting).
Georg Brandl3961f182008-05-05 20:53:39 +0000205
Raymond Hettinger91852ca2009-03-19 19:19:03 +0000206 *object_pairs_hook* is an optional function that will be called with the
Andrew M. Kuchling19672002009-03-30 22:29:15 +0000207 result of any object literal decoded with an ordered list of pairs. The
Raymond Hettinger91852ca2009-03-19 19:19:03 +0000208 return value of *object_pairs_hook* will be used instead of the
209 :class:`dict`. This feature can be used to implement custom decoders that
210 rely on the order that the key and value pairs are decoded (for example,
211 :func:`collections.OrderedDict` will remember the order of insertion). If
212 *object_hook* is also defined, the *object_pairs_hook* takes priority.
213
214 .. versionchanged:: 2.7
215 Added support for *object_pairs_hook*.
216
Georg Brandl3961f182008-05-05 20:53:39 +0000217 *parse_float*, if specified, will be called with the string of every JSON
218 float to be decoded. By default, this is equivalent to ``float(num_str)``.
219 This can be used to use another datatype or parser for JSON floats
220 (e.g. :class:`decimal.Decimal`).
221
222 *parse_int*, if specified, will be called with the string of every JSON int
223 to be decoded. By default, this is equivalent to ``int(num_str)``. This can
224 be used to use another datatype or parser for JSON integers
225 (e.g. :class:`float`).
226
227 *parse_constant*, if specified, will be called with one of the following
Hynek Schlawack019935f2012-05-16 18:02:54 +0200228 strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``.
229 This can be used to raise an exception if invalid JSON numbers
Georg Brandl3961f182008-05-05 20:53:39 +0000230 are encountered.
Brett Cannon4b964f92008-05-05 20:21:38 +0000231
Hynek Schlawack897b2782012-05-20 11:50:41 +0200232 .. versionchanged:: 2.7
233 *parse_constant* doesn't get called on 'null', 'true', 'false' anymore.
234
Brett Cannon4b964f92008-05-05 20:21:38 +0000235 To use a custom :class:`JSONDecoder` subclass, specify it with the ``cls``
Georg Brandldb949b82010-10-15 17:04:45 +0000236 kwarg; otherwise :class:`JSONDecoder` is used. Additional keyword arguments
237 will be passed to the constructor of the class.
Brett Cannon4b964f92008-05-05 20:21:38 +0000238
239
Raymond Hettinger91852ca2009-03-19 19:19:03 +0000240.. function:: loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Georg Brandl3961f182008-05-05 20:53:39 +0000241
242 Deserialize *s* (a :class:`str` or :class:`unicode` instance containing a JSON
243 document) to a Python object.
244
245 If *s* is a :class:`str` instance and is encoded with an ASCII based encoding
246 other than UTF-8 (e.g. latin-1), then an appropriate *encoding* name must be
247 specified. Encodings that are not ASCII based (such as UCS-2) are not
248 allowed and should be decoded to :class:`unicode` first.
249
Georg Brandlc6301952010-05-10 21:02:51 +0000250 The other arguments have the same meaning as in :func:`load`.
Georg Brandl3961f182008-05-05 20:53:39 +0000251
252
Antoine Pitrouf3e0a692012-08-24 19:46:17 +0200253Encoders and Decoders
Brett Cannon4b964f92008-05-05 20:21:38 +0000254---------------------
255
Raymond Hettinger91852ca2009-03-19 19:19:03 +0000256.. class:: JSONDecoder([encoding[, object_hook[, parse_float[, parse_int[, parse_constant[, strict[, object_pairs_hook]]]]]]])
Brett Cannon4b964f92008-05-05 20:21:38 +0000257
Georg Brandl3961f182008-05-05 20:53:39 +0000258 Simple JSON decoder.
Brett Cannon4b964f92008-05-05 20:21:38 +0000259
260 Performs the following translations in decoding by default:
261
262 +---------------+-------------------+
263 | JSON | Python |
264 +===============+===================+
265 | object | dict |
266 +---------------+-------------------+
267 | array | list |
268 +---------------+-------------------+
269 | string | unicode |
270 +---------------+-------------------+
271 | number (int) | int, long |
272 +---------------+-------------------+
273 | number (real) | float |
274 +---------------+-------------------+
275 | true | True |
276 +---------------+-------------------+
277 | false | False |
278 +---------------+-------------------+
279 | null | None |
280 +---------------+-------------------+
281
282 It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their
283 corresponding ``float`` values, which is outside the JSON spec.
284
Georg Brandl3961f182008-05-05 20:53:39 +0000285 *encoding* determines the encoding used to interpret any :class:`str` objects
286 decoded by this instance (UTF-8 by default). It has no effect when decoding
287 :class:`unicode` objects.
Brett Cannon4b964f92008-05-05 20:21:38 +0000288
Georg Brandl3961f182008-05-05 20:53:39 +0000289 Note that currently only encodings that are a superset of ASCII work, strings
290 of other encodings should be passed in as :class:`unicode`.
Brett Cannon4b964f92008-05-05 20:21:38 +0000291
292 *object_hook*, if specified, will be called with the result of every JSON
293 object decoded and its return value will be used in place of the given
Georg Brandl3961f182008-05-05 20:53:39 +0000294 :class:`dict`. This can be used to provide custom deserializations (e.g. to
Brett Cannon4b964f92008-05-05 20:21:38 +0000295 support JSON-RPC class hinting).
296
Raymond Hettinger91852ca2009-03-19 19:19:03 +0000297 *object_pairs_hook*, if specified will be called with the result of every
298 JSON object decoded with an ordered list of pairs. The return value of
299 *object_pairs_hook* will be used instead of the :class:`dict`. This
300 feature can be used to implement custom decoders that rely on the order
301 that the key and value pairs are decoded (for example,
302 :func:`collections.OrderedDict` will remember the order of insertion). If
303 *object_hook* is also defined, the *object_pairs_hook* takes priority.
304
305 .. versionchanged:: 2.7
306 Added support for *object_pairs_hook*.
307
Brett Cannon4b964f92008-05-05 20:21:38 +0000308 *parse_float*, if specified, will be called with the string of every JSON
Georg Brandl3961f182008-05-05 20:53:39 +0000309 float to be decoded. By default, this is equivalent to ``float(num_str)``.
310 This can be used to use another datatype or parser for JSON floats
311 (e.g. :class:`decimal.Decimal`).
Brett Cannon4b964f92008-05-05 20:21:38 +0000312
313 *parse_int*, if specified, will be called with the string of every JSON int
Georg Brandl3961f182008-05-05 20:53:39 +0000314 to be decoded. By default, this is equivalent to ``int(num_str)``. This can
315 be used to use another datatype or parser for JSON integers
316 (e.g. :class:`float`).
Brett Cannon4b964f92008-05-05 20:21:38 +0000317
318 *parse_constant*, if specified, will be called with one of the following
Georg Brandl3961f182008-05-05 20:53:39 +0000319 strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``, ``'null'``, ``'true'``,
320 ``'false'``. This can be used to raise an exception if invalid JSON numbers
321 are encountered.
Brett Cannon4b964f92008-05-05 20:21:38 +0000322
Georg Brandldb949b82010-10-15 17:04:45 +0000323 If *strict* is ``False`` (``True`` is the default), then control characters
324 will be allowed inside strings. Control characters in this context are
325 those with character codes in the 0-31 range, including ``'\t'`` (tab),
326 ``'\n'``, ``'\r'`` and ``'\0'``.
327
Brett Cannon4b964f92008-05-05 20:21:38 +0000328
329 .. method:: decode(s)
330
Georg Brandl3961f182008-05-05 20:53:39 +0000331 Return the Python representation of *s* (a :class:`str` or
332 :class:`unicode` instance containing a JSON document)
Brett Cannon4b964f92008-05-05 20:21:38 +0000333
334 .. method:: raw_decode(s)
335
Georg Brandl3961f182008-05-05 20:53:39 +0000336 Decode a JSON document from *s* (a :class:`str` or :class:`unicode`
337 beginning with a JSON document) and return a 2-tuple of the Python
338 representation and the index in *s* where the document ended.
Brett Cannon4b964f92008-05-05 20:21:38 +0000339
Georg Brandl3961f182008-05-05 20:53:39 +0000340 This can be used to decode a JSON document from a string that may have
341 extraneous data at the end.
Brett Cannon4b964f92008-05-05 20:21:38 +0000342
343
344.. class:: JSONEncoder([skipkeys[, ensure_ascii[, check_circular[, allow_nan[, sort_keys[, indent[, separators[, encoding[, default]]]]]]]]])
345
Georg Brandl3961f182008-05-05 20:53:39 +0000346 Extensible JSON encoder for Python data structures.
Brett Cannon4b964f92008-05-05 20:21:38 +0000347
348 Supports the following objects and types by default:
349
350 +-------------------+---------------+
351 | Python | JSON |
352 +===================+===============+
353 | dict | object |
354 +-------------------+---------------+
355 | list, tuple | array |
356 +-------------------+---------------+
357 | str, unicode | string |
358 +-------------------+---------------+
359 | int, long, float | number |
360 +-------------------+---------------+
361 | True | true |
362 +-------------------+---------------+
363 | False | false |
364 +-------------------+---------------+
365 | None | null |
366 +-------------------+---------------+
367
368 To extend this to recognize other objects, subclass and implement a
Georg Brandl3961f182008-05-05 20:53:39 +0000369 :meth:`default` method with another method that returns a serializable object
Brett Cannon4b964f92008-05-05 20:21:38 +0000370 for ``o`` if possible, otherwise it should call the superclass implementation
371 (to raise :exc:`TypeError`).
372
373 If *skipkeys* is ``False`` (the default), then it is a :exc:`TypeError` to
374 attempt encoding of keys that are not str, int, long, float or None. If
375 *skipkeys* is ``True``, such items are simply skipped.
376
Petri Lehtinenf9e1f112012-09-01 07:27:58 +0300377 If *ensure_ascii* is ``True`` (the default), all non-ASCII characters in the
378 output are escaped with ``\uXXXX`` sequences, and the results are
379 :class:`str` instances consisting of ASCII characters only. If
380 *ensure_ascii* is ``False``, a result may be a :class:`unicode`
381 instance. This usually happens if the input contains unicode strings or the
382 *encoding* parameter is used.
Brett Cannon4b964f92008-05-05 20:21:38 +0000383
384 If *check_circular* is ``True`` (the default), then lists, dicts, and custom
385 encoded objects will be checked for circular references during encoding to
386 prevent an infinite recursion (which would cause an :exc:`OverflowError`).
387 Otherwise, no such check takes place.
388
Georg Brandl3961f182008-05-05 20:53:39 +0000389 If *allow_nan* is ``True`` (the default), then ``NaN``, ``Infinity``, and
390 ``-Infinity`` will be encoded as such. This behavior is not JSON
391 specification compliant, but is consistent with most JavaScript based
392 encoders and decoders. Otherwise, it will be a :exc:`ValueError` to encode
393 such floats.
Brett Cannon4b964f92008-05-05 20:21:38 +0000394
Georg Brandl21946af2010-10-06 09:28:45 +0000395 If *sort_keys* is ``True`` (default ``False``), then the output of dictionaries
Brett Cannon4b964f92008-05-05 20:21:38 +0000396 will be sorted by key; this is useful for regression tests to ensure that
397 JSON serializations can be compared on a day-to-day basis.
398
Georg Brandl3961f182008-05-05 20:53:39 +0000399 If *indent* is a non-negative integer (it is ``None`` by default), then JSON
Brett Cannon4b964f92008-05-05 20:21:38 +0000400 array elements and object members will be pretty-printed with that indent
401 level. An indent level of 0 will only insert newlines. ``None`` is the most
402 compact representation.
403
Georg Brandl3961f182008-05-05 20:53:39 +0000404 If specified, *separators* should be an ``(item_separator, key_separator)``
405 tuple. The default is ``(', ', ': ')``. To get the most compact JSON
Brett Cannon4b964f92008-05-05 20:21:38 +0000406 representation, you should specify ``(',', ':')`` to eliminate whitespace.
407
408 If specified, *default* is a function that gets called for objects that can't
409 otherwise be serialized. It should return a JSON encodable version of the
410 object or raise a :exc:`TypeError`.
411
412 If *encoding* is not ``None``, then all input strings will be transformed
413 into unicode using that encoding prior to JSON-encoding. The default is
414 UTF-8.
415
416
417 .. method:: default(o)
418
419 Implement this method in a subclass such that it returns a serializable
420 object for *o*, or calls the base implementation (to raise a
421 :exc:`TypeError`).
422
423 For example, to support arbitrary iterators, you could implement default
424 like this::
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000425
Brett Cannon4b964f92008-05-05 20:21:38 +0000426 def default(self, o):
427 try:
Georg Brandl1379ae02008-09-24 09:47:55 +0000428 iterable = iter(o)
Brett Cannon4b964f92008-05-05 20:21:38 +0000429 except TypeError:
Georg Brandl1379ae02008-09-24 09:47:55 +0000430 pass
Brett Cannon4b964f92008-05-05 20:21:38 +0000431 else:
432 return list(iterable)
433 return JSONEncoder.default(self, o)
434
435
436 .. method:: encode(o)
437
Georg Brandl3961f182008-05-05 20:53:39 +0000438 Return a JSON string representation of a Python data structure, *o*. For
Brett Cannon4b964f92008-05-05 20:21:38 +0000439 example::
440
441 >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
442 '{"foo": ["bar", "baz"]}'
443
444
445 .. method:: iterencode(o)
446
447 Encode the given object, *o*, and yield each string representation as
Georg Brandl3961f182008-05-05 20:53:39 +0000448 available. For example::
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000449
Brett Cannon4b964f92008-05-05 20:21:38 +0000450 for chunk in JSONEncoder().iterencode(bigobject):
451 mysocket.write(chunk)
Antoine Pitrouf3e0a692012-08-24 19:46:17 +0200452
453
454Standard Compliance
455-------------------
456
457The JSON format is specified by :rfc:`4627`. This section details this
458module's level of compliance with the RFC. For simplicity,
459:class:`JSONEncoder` and :class:`JSONDecoder` subclasses, and parameters other
460than those explicitly mentioned, are not considered.
461
462This module does not comply with the RFC in a strict fashion, implementing some
463extensions that are valid JavaScript but not valid JSON. In particular:
464
465- Top-level non-object, non-array values are accepted and output;
466- Infinite and NaN number values are accepted and output;
467- Repeated names within an object are accepted, and only the value of the last
468 name-value pair is used.
469
470Since the RFC permits RFC-compliant parsers to accept input texts that are not
471RFC-compliant, this module's deserializer is technically RFC-compliant under
472default settings.
473
474Character Encodings
475^^^^^^^^^^^^^^^^^^^
476
477The RFC recommends that JSON be represented using either UTF-8, UTF-16, or
478UTF-32, with UTF-8 being the default. Accordingly, this module uses UTF-8 as
479the default for its *encoding* parameter.
480
481This module's deserializer only directly works with ASCII-compatible encodings;
482UTF-16, UTF-32, and other ASCII-incompatible encodings require the use of
483workarounds described in the documentation for the deserializer's *encoding*
484parameter.
485
486The RFC also non-normatively describes a limited encoding detection technique
487for JSON texts; this module's deserializer does not implement this or any other
488kind of encoding detection.
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
494
495Top-level Non-Object, Non-Array Values
496^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
497
498The RFC specifies that the top-level value of a JSON text must be either a
499JSON object or array (Python :class:`dict` or :class:`list`). This module's
500deserializer also accepts input texts consisting solely of a
501JSON null, boolean, number, or string value::
502
503 >>> just_a_json_string = '"spam and eggs"' # Not by itself a valid JSON text
504 >>> json.loads(just_a_json_string)
505 u'spam and eggs'
506
507This module itself does not include a way to request that such input texts be
508regarded as illegal. Likewise, this module's serializer also accepts single
509Python :data:`None`, :class:`bool`, numeric, and :class:`str`
510values as input and will generate output texts consisting solely of a top-level
511JSON null, boolean, number, or string value without raising an exception::
512
513 >>> neither_a_list_nor_a_dict = u"spam and eggs"
514 >>> json.dumps(neither_a_list_nor_a_dict) # The result is not a valid JSON text
515 '"spam and eggs"'
516
517This module's serializer does not itself include a way to enforce the
518aforementioned constraint.
519
520
521Infinite and NaN Number Values
522^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
523
524The RFC does not permit the representation of infinite or NaN number values.
525Despite that, by default, this module accepts and outputs ``Infinity``,
526``-Infinity``, and ``NaN`` as if they were valid JSON number literal values::
527
528 >>> # Neither of these calls raises an exception, but the results are not valid JSON
529 >>> json.dumps(float('-inf'))
530 '-Infinity'
531 >>> json.dumps(float('nan'))
532 'NaN'
533 >>> # Same when deserializing
534 >>> json.loads('-Infinity')
535 -inf
536 >>> json.loads('NaN')
537 nan
538
539In the serializer, the *allow_nan* parameter can be used to alter this
540behavior. In the deserializer, the *parse_constant* parameter can be used to
541alter this behavior.
542
543
544Repeated Names Within an Object
545^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
546
547The RFC specifies that the names within a JSON object should be unique, but
548does not specify how repeated names in JSON objects should be handled. By
549default, this module does not raise an exception; instead, it ignores all but
550the last name-value pair for a given name::
551
552 >>> weird_json = '{"x": 1, "x": 2, "x": 3}'
553 >>> json.loads(weird_json)
554 {u'x': 3}
555
556The *object_pairs_hook* parameter can be used to alter this behavior.