blob: a3c6bb0efbe6313380495663fd04c18f206a79b5 [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
Ezio Melotti3a237eb2012-11-29 00:22:30 +020046 >>> print json.dumps({'4': 5, '6': 7}, sort_keys=True,
47 ... indent=4, separators=(',', ': '))
Brett Cannon4b964f92008-05-05 20:21:38 +000048 {
Georg Brandlc62ef8b2009-01-03 20:55:06 +000049 "4": 5,
Brett Cannon4b964f92008-05-05 20:21:38 +000050 "6": 7
51 }
52
53Decoding JSON::
Georg Brandlc62ef8b2009-01-03 20:55:06 +000054
Brett Cannon4b964f92008-05-05 20:21:38 +000055 >>> import json
56 >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
57 [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
58 >>> json.loads('"\\"foo\\bar"')
59 u'"foo\x08ar'
60 >>> from StringIO import StringIO
61 >>> io = StringIO('["streaming API"]')
62 >>> json.load(io)
63 [u'streaming API']
64
65Specializing JSON object decoding::
66
67 >>> import json
68 >>> def as_complex(dct):
69 ... if '__complex__' in dct:
70 ... return complex(dct['real'], dct['imag'])
71 ... return dct
Georg Brandlc62ef8b2009-01-03 20:55:06 +000072 ...
Brett Cannon4b964f92008-05-05 20:21:38 +000073 >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
74 ... object_hook=as_complex)
75 (1+2j)
76 >>> import decimal
77 >>> json.loads('1.1', parse_float=decimal.Decimal)
78 Decimal('1.1')
79
Georg Brandl3961f182008-05-05 20:53:39 +000080Extending :class:`JSONEncoder`::
Georg Brandlc62ef8b2009-01-03 20:55:06 +000081
Brett Cannon4b964f92008-05-05 20:21:38 +000082 >>> import json
83 >>> class ComplexEncoder(json.JSONEncoder):
84 ... def default(self, obj):
85 ... if isinstance(obj, complex):
86 ... return [obj.real, obj.imag]
R David Murray35893b72013-03-17 22:06:18 -040087 ... # Let the base class default method raise the TypeError
Brett Cannon4b964f92008-05-05 20:21:38 +000088 ... return json.JSONEncoder.default(self, obj)
Georg Brandlc62ef8b2009-01-03 20:55:06 +000089 ...
Brett Cannon4b964f92008-05-05 20:21:38 +000090 >>> dumps(2 + 1j, cls=ComplexEncoder)
91 '[2.0, 1.0]'
92 >>> ComplexEncoder().encode(2 + 1j)
93 '[2.0, 1.0]'
94 >>> list(ComplexEncoder().iterencode(2 + 1j))
95 ['[', '2.0', ', ', '1.0', ']']
Georg Brandlc62ef8b2009-01-03 20:55:06 +000096
Brett Cannon4b964f92008-05-05 20:21:38 +000097
98.. highlight:: none
99
100Using json.tool from the shell to validate and pretty-print::
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000101
Brett Cannon4b964f92008-05-05 20:21:38 +0000102 $ echo '{"json":"obj"}' | python -mjson.tool
103 {
104 "json": "obj"
105 }
Antoine Pitroud9a51372012-06-29 01:58:26 +0200106 $ echo '{1.2:3.4}' | python -mjson.tool
Serhiy Storchaka49d40222013-02-21 20:17:54 +0200107 Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
Brett Cannon4b964f92008-05-05 20:21:38 +0000108
109.. highlight:: python
110
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000111.. note::
Brett Cannon4b964f92008-05-05 20:21:38 +0000112
Antoine Pitrouf3e0a692012-08-24 19:46:17 +0200113 JSON is a subset of `YAML <http://yaml.org/>`_ 1.2. The JSON produced by
114 this module's default settings (in particular, the default *separators*
115 value) is also a subset of YAML 1.0 and 1.1. This module can thus also be
116 used as a YAML serializer.
Brett Cannon4b964f92008-05-05 20:21:38 +0000117
118
119Basic Usage
120-----------
121
Andrew Svetlov41c25ba2012-10-28 14:58:52 +0200122.. function:: dump(obj, fp, skipkeys=False, ensure_ascii=True, \
123 check_circular=True, allow_nan=True, cls=None, \
124 indent=None, separators=None, encoding="utf-8", \
125 default=None, sort_keys=False, **kw)
Brett Cannon4b964f92008-05-05 20:21:38 +0000126
Georg Brandl3961f182008-05-05 20:53:39 +0000127 Serialize *obj* as a JSON formatted stream to *fp* (a ``.write()``-supporting
Antoine Pitrou85ede8d2012-08-24 19:49:08 +0200128 :term:`file-like object`).
Brett Cannon4b964f92008-05-05 20:21:38 +0000129
Georg Brandl3961f182008-05-05 20:53:39 +0000130 If *skipkeys* is ``True`` (default: ``False``), then dict keys that are not
131 of a basic type (:class:`str`, :class:`unicode`, :class:`int`, :class:`long`,
132 :class:`float`, :class:`bool`, ``None``) will be skipped instead of raising a
133 :exc:`TypeError`.
Brett Cannon4b964f92008-05-05 20:21:38 +0000134
Petri Lehtinenf9e1f112012-09-01 07:27:58 +0300135 If *ensure_ascii* is ``True`` (the default), all non-ASCII characters in the
136 output are escaped with ``\uXXXX`` sequences, and the result is a
137 :class:`str` instance consisting of ASCII characters only. If
138 *ensure_ascii* is ``False``, some chunks written to *fp* may be
139 :class:`unicode` instances. This usually happens because the input contains
140 unicode strings or the *encoding* parameter is used. Unless ``fp.write()``
141 explicitly understands :class:`unicode` (as in :func:`codecs.getwriter`)
142 this is likely to cause an error.
Brett Cannon4b964f92008-05-05 20:21:38 +0000143
Georg Brandl3961f182008-05-05 20:53:39 +0000144 If *check_circular* is ``False`` (default: ``True``), then the circular
145 reference check for container types will be skipped and a circular reference
146 will result in an :exc:`OverflowError` (or worse).
Brett Cannon4b964f92008-05-05 20:21:38 +0000147
Georg Brandl3961f182008-05-05 20:53:39 +0000148 If *allow_nan* is ``False`` (default: ``True``), then it will be a
149 :exc:`ValueError` to serialize out of range :class:`float` values (``nan``,
150 ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of
151 using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
Brett Cannon4b964f92008-05-05 20:21:38 +0000152
Georg Brandl3961f182008-05-05 20:53:39 +0000153 If *indent* is a non-negative integer, then JSON array elements and object
R David Murrayea8b6ef2011-04-12 21:00:26 -0400154 members will be pretty-printed with that indent level. An indent level of 0,
155 or negative, will only insert newlines. ``None`` (the default) selects the
156 most compact representation.
Brett Cannon4b964f92008-05-05 20:21:38 +0000157
Ezio Melotti3a237eb2012-11-29 00:22:30 +0200158 .. note::
159
160 Since the default item separator is ``', '``, the output might include
161 trailing whitespace when *indent* is specified. You can use
162 ``separators=(',', ': ')`` to avoid this.
163
Georg Brandl3961f182008-05-05 20:53:39 +0000164 If *separators* is an ``(item_separator, dict_separator)`` tuple, then it
165 will be used instead of the default ``(', ', ': ')`` separators. ``(',',
166 ':')`` is the most compact JSON representation.
Brett Cannon4b964f92008-05-05 20:21:38 +0000167
Georg Brandl3961f182008-05-05 20:53:39 +0000168 *encoding* is the character encoding for str instances, default is UTF-8.
Brett Cannon4b964f92008-05-05 20:21:38 +0000169
Georg Brandl3961f182008-05-05 20:53:39 +0000170 *default(obj)* is a function that should return a serializable version of
171 *obj* or raise :exc:`TypeError`. The default simply raises :exc:`TypeError`.
Brett Cannon4b964f92008-05-05 20:21:38 +0000172
Andrew Svetlov41c25ba2012-10-28 14:58:52 +0200173 If *sort_keys* is ``True`` (default: ``False``), then the output of
174 dictionaries will be sorted by key.
175
Georg Brandlfc29f272009-01-02 20:25:14 +0000176 To use a custom :class:`JSONEncoder` subclass (e.g. one that overrides the
Georg Brandl3961f182008-05-05 20:53:39 +0000177 :meth:`default` method to serialize additional types), specify it with the
Georg Brandldb949b82010-10-15 17:04:45 +0000178 *cls* kwarg; otherwise :class:`JSONEncoder` is used.
Brett Cannon4b964f92008-05-05 20:21:38 +0000179
Ezio Melotti6033d262011-04-15 07:37:00 +0300180 .. note::
181
182 Unlike :mod:`pickle` and :mod:`marshal`, JSON is not a framed protocol so
183 trying to serialize more objects with repeated calls to :func:`dump` and
184 the same *fp* will result in an invalid JSON file.
Brett Cannon4b964f92008-05-05 20:21:38 +0000185
Andrew Svetlov41c25ba2012-10-28 14:58:52 +0200186.. function:: dumps(obj, skipkeys=False, ensure_ascii=True, \
187 check_circular=True, allow_nan=True, cls=None, \
188 indent=None, separators=None, encoding="utf-8", \
189 default=None, sort_keys=False, **kw)
Brett Cannon4b964f92008-05-05 20:21:38 +0000190
Petri Lehtinenf9e1f112012-09-01 07:27:58 +0300191 Serialize *obj* to a JSON formatted :class:`str`. If *ensure_ascii* is
192 ``False``, the result may contain non-ASCII characters and the return value
193 may be a :class:`unicode` instance.
Brett Cannon4b964f92008-05-05 20:21:38 +0000194
Petri Lehtinenf9e1f112012-09-01 07:27:58 +0300195 The arguments have the same meaning as in :func:`dump`.
Brett Cannon4b964f92008-05-05 20:21:38 +0000196
Senthil Kumarane3d73542012-03-17 00:37:38 -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 Reedy3d08f252013-03-08 19:35:15 -0500201 coerced to strings. As a result of this, if a dictionary is converted
Senthil Kumarane3d73542012-03-17 00:37:38 -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.
Brett Cannon4b964f92008-05-05 20:21:38 +0000205
Raymond Hettinger91852ca2009-03-19 19:19:03 +0000206.. function:: load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Brett Cannon4b964f92008-05-05 20:21:38 +0000207
Antoine Pitrou85ede8d2012-08-24 19:49:08 +0200208 Deserialize *fp* (a ``.read()``-supporting :term:`file-like object`
209 containing a JSON document) to a Python object.
Brett Cannon4b964f92008-05-05 20:21:38 +0000210
Georg Brandl3961f182008-05-05 20:53:39 +0000211 If the contents of *fp* are encoded with an ASCII based encoding other than
212 UTF-8 (e.g. latin-1), then an appropriate *encoding* name must be specified.
213 Encodings that are not ASCII based (such as UCS-2) are not allowed, and
Georg Brandl49cc4ea2009-04-23 08:44:57 +0000214 should be wrapped with ``codecs.getreader(encoding)(fp)``, or simply decoded
Georg Brandl3961f182008-05-05 20:53:39 +0000215 to a :class:`unicode` object and passed to :func:`loads`.
Brett Cannon4b964f92008-05-05 20:21:38 +0000216
217 *object_hook* is an optional function that will be called with the result of
Andrew M. Kuchling19672002009-03-30 22:29:15 +0000218 any object literal decoded (a :class:`dict`). The return value of
Georg Brandl3961f182008-05-05 20:53:39 +0000219 *object_hook* will be used instead of the :class:`dict`. This feature can be used
Antoine Pitrouf3e0a692012-08-24 19:46:17 +0200220 to implement custom decoders (e.g. `JSON-RPC <http://www.jsonrpc.org>`_
221 class hinting).
Georg Brandl3961f182008-05-05 20:53:39 +0000222
Raymond Hettinger91852ca2009-03-19 19:19:03 +0000223 *object_pairs_hook* is an optional function that will be called with the
Andrew M. Kuchling19672002009-03-30 22:29:15 +0000224 result of any object literal decoded with an ordered list of pairs. The
Raymond Hettinger91852ca2009-03-19 19:19:03 +0000225 return value of *object_pairs_hook* will be used instead of the
226 :class:`dict`. This feature can be used to implement custom decoders that
227 rely on the order that the key and value pairs are decoded (for example,
228 :func:`collections.OrderedDict` will remember the order of insertion). If
229 *object_hook* is also defined, the *object_pairs_hook* takes priority.
230
231 .. versionchanged:: 2.7
232 Added support for *object_pairs_hook*.
233
Georg Brandl3961f182008-05-05 20:53:39 +0000234 *parse_float*, if specified, will be called with the string of every JSON
235 float to be decoded. By default, this is equivalent to ``float(num_str)``.
236 This can be used to use another datatype or parser for JSON floats
237 (e.g. :class:`decimal.Decimal`).
238
239 *parse_int*, if specified, will be called with the string of every JSON int
240 to be decoded. By default, this is equivalent to ``int(num_str)``. This can
241 be used to use another datatype or parser for JSON integers
242 (e.g. :class:`float`).
243
244 *parse_constant*, if specified, will be called with one of the following
Hynek Schlawack019935f2012-05-16 18:02:54 +0200245 strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``.
246 This can be used to raise an exception if invalid JSON numbers
Georg Brandl3961f182008-05-05 20:53:39 +0000247 are encountered.
Brett Cannon4b964f92008-05-05 20:21:38 +0000248
Hynek Schlawack897b2782012-05-20 11:50:41 +0200249 .. versionchanged:: 2.7
250 *parse_constant* doesn't get called on 'null', 'true', 'false' anymore.
251
Brett Cannon4b964f92008-05-05 20:21:38 +0000252 To use a custom :class:`JSONDecoder` subclass, specify it with the ``cls``
Georg Brandldb949b82010-10-15 17:04:45 +0000253 kwarg; otherwise :class:`JSONDecoder` is used. Additional keyword arguments
254 will be passed to the constructor of the class.
Brett Cannon4b964f92008-05-05 20:21:38 +0000255
256
Raymond Hettinger91852ca2009-03-19 19:19:03 +0000257.. function:: loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Georg Brandl3961f182008-05-05 20:53:39 +0000258
259 Deserialize *s* (a :class:`str` or :class:`unicode` instance containing a JSON
260 document) to a Python object.
261
262 If *s* is a :class:`str` instance and is encoded with an ASCII based encoding
263 other than UTF-8 (e.g. latin-1), then an appropriate *encoding* name must be
264 specified. Encodings that are not ASCII based (such as UCS-2) are not
265 allowed and should be decoded to :class:`unicode` first.
266
Georg Brandlc6301952010-05-10 21:02:51 +0000267 The other arguments have the same meaning as in :func:`load`.
Georg Brandl3961f182008-05-05 20:53:39 +0000268
269
Antoine Pitrouf3e0a692012-08-24 19:46:17 +0200270Encoders and Decoders
Brett Cannon4b964f92008-05-05 20:21:38 +0000271---------------------
272
Raymond Hettinger91852ca2009-03-19 19:19:03 +0000273.. class:: JSONDecoder([encoding[, object_hook[, parse_float[, parse_int[, parse_constant[, strict[, object_pairs_hook]]]]]]])
Brett Cannon4b964f92008-05-05 20:21:38 +0000274
Georg Brandl3961f182008-05-05 20:53:39 +0000275 Simple JSON decoder.
Brett Cannon4b964f92008-05-05 20:21:38 +0000276
277 Performs the following translations in decoding by default:
278
279 +---------------+-------------------+
280 | JSON | Python |
281 +===============+===================+
282 | object | dict |
283 +---------------+-------------------+
284 | array | list |
285 +---------------+-------------------+
286 | string | unicode |
287 +---------------+-------------------+
288 | number (int) | int, long |
289 +---------------+-------------------+
290 | number (real) | float |
291 +---------------+-------------------+
292 | true | True |
293 +---------------+-------------------+
294 | false | False |
295 +---------------+-------------------+
296 | null | None |
297 +---------------+-------------------+
298
299 It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their
300 corresponding ``float`` values, which is outside the JSON spec.
301
Georg Brandl3961f182008-05-05 20:53:39 +0000302 *encoding* determines the encoding used to interpret any :class:`str` objects
303 decoded by this instance (UTF-8 by default). It has no effect when decoding
304 :class:`unicode` objects.
Brett Cannon4b964f92008-05-05 20:21:38 +0000305
Georg Brandl3961f182008-05-05 20:53:39 +0000306 Note that currently only encodings that are a superset of ASCII work, strings
307 of other encodings should be passed in as :class:`unicode`.
Brett Cannon4b964f92008-05-05 20:21:38 +0000308
309 *object_hook*, if specified, will be called with the result of every JSON
310 object decoded and its return value will be used in place of the given
Georg Brandl3961f182008-05-05 20:53:39 +0000311 :class:`dict`. This can be used to provide custom deserializations (e.g. to
Brett Cannon4b964f92008-05-05 20:21:38 +0000312 support JSON-RPC class hinting).
313
Raymond Hettinger91852ca2009-03-19 19:19:03 +0000314 *object_pairs_hook*, if specified will be called with the result of every
315 JSON object decoded with an ordered list of pairs. The return value of
316 *object_pairs_hook* will be used instead of the :class:`dict`. This
317 feature can be used to implement custom decoders that rely on the order
318 that the key and value pairs are decoded (for example,
319 :func:`collections.OrderedDict` will remember the order of insertion). If
320 *object_hook* is also defined, the *object_pairs_hook* takes priority.
321
322 .. versionchanged:: 2.7
323 Added support for *object_pairs_hook*.
324
Brett Cannon4b964f92008-05-05 20:21:38 +0000325 *parse_float*, if specified, will be called with the string of every JSON
Georg Brandl3961f182008-05-05 20:53:39 +0000326 float to be decoded. By default, this is equivalent to ``float(num_str)``.
327 This can be used to use another datatype or parser for JSON floats
328 (e.g. :class:`decimal.Decimal`).
Brett Cannon4b964f92008-05-05 20:21:38 +0000329
330 *parse_int*, if specified, will be called with the string of every JSON int
Georg Brandl3961f182008-05-05 20:53:39 +0000331 to be decoded. By default, this is equivalent to ``int(num_str)``. This can
332 be used to use another datatype or parser for JSON integers
333 (e.g. :class:`float`).
Brett Cannon4b964f92008-05-05 20:21:38 +0000334
335 *parse_constant*, if specified, will be called with one of the following
Georg Brandl3961f182008-05-05 20:53:39 +0000336 strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``, ``'null'``, ``'true'``,
337 ``'false'``. This can be used to raise an exception if invalid JSON numbers
338 are encountered.
Brett Cannon4b964f92008-05-05 20:21:38 +0000339
Georg Brandldb949b82010-10-15 17:04:45 +0000340 If *strict* is ``False`` (``True`` is the default), then control characters
341 will be allowed inside strings. Control characters in this context are
342 those with character codes in the 0-31 range, including ``'\t'`` (tab),
343 ``'\n'``, ``'\r'`` and ``'\0'``.
344
Brett Cannon4b964f92008-05-05 20:21:38 +0000345
346 .. method:: decode(s)
347
Georg Brandl3961f182008-05-05 20:53:39 +0000348 Return the Python representation of *s* (a :class:`str` or
349 :class:`unicode` instance containing a JSON document)
Brett Cannon4b964f92008-05-05 20:21:38 +0000350
351 .. method:: raw_decode(s)
352
Georg Brandl3961f182008-05-05 20:53:39 +0000353 Decode a JSON document from *s* (a :class:`str` or :class:`unicode`
354 beginning with a JSON document) and return a 2-tuple of the Python
355 representation and the index in *s* where the document ended.
Brett Cannon4b964f92008-05-05 20:21:38 +0000356
Georg Brandl3961f182008-05-05 20:53:39 +0000357 This can be used to decode a JSON document from a string that may have
358 extraneous data at the end.
Brett Cannon4b964f92008-05-05 20:21:38 +0000359
360
361.. class:: JSONEncoder([skipkeys[, ensure_ascii[, check_circular[, allow_nan[, sort_keys[, indent[, separators[, encoding[, default]]]]]]]]])
362
Georg Brandl3961f182008-05-05 20:53:39 +0000363 Extensible JSON encoder for Python data structures.
Brett Cannon4b964f92008-05-05 20:21:38 +0000364
365 Supports the following objects and types by default:
366
367 +-------------------+---------------+
368 | Python | JSON |
369 +===================+===============+
370 | dict | object |
371 +-------------------+---------------+
372 | list, tuple | array |
373 +-------------------+---------------+
374 | str, unicode | string |
375 +-------------------+---------------+
376 | int, long, float | number |
377 +-------------------+---------------+
378 | True | true |
379 +-------------------+---------------+
380 | False | false |
381 +-------------------+---------------+
382 | None | null |
383 +-------------------+---------------+
384
385 To extend this to recognize other objects, subclass and implement a
Georg Brandl3961f182008-05-05 20:53:39 +0000386 :meth:`default` method with another method that returns a serializable object
Brett Cannon4b964f92008-05-05 20:21:38 +0000387 for ``o`` if possible, otherwise it should call the superclass implementation
388 (to raise :exc:`TypeError`).
389
390 If *skipkeys* is ``False`` (the default), then it is a :exc:`TypeError` to
391 attempt encoding of keys that are not str, int, long, float or None. If
392 *skipkeys* is ``True``, such items are simply skipped.
393
Petri Lehtinenf9e1f112012-09-01 07:27:58 +0300394 If *ensure_ascii* is ``True`` (the default), all non-ASCII characters in the
395 output are escaped with ``\uXXXX`` sequences, and the results are
396 :class:`str` instances consisting of ASCII characters only. If
397 *ensure_ascii* is ``False``, a result may be a :class:`unicode`
398 instance. This usually happens if the input contains unicode strings or the
399 *encoding* parameter is used.
Brett Cannon4b964f92008-05-05 20:21:38 +0000400
401 If *check_circular* is ``True`` (the default), then lists, dicts, and custom
402 encoded objects will be checked for circular references during encoding to
403 prevent an infinite recursion (which would cause an :exc:`OverflowError`).
404 Otherwise, no such check takes place.
405
Georg Brandl3961f182008-05-05 20:53:39 +0000406 If *allow_nan* is ``True`` (the default), then ``NaN``, ``Infinity``, and
407 ``-Infinity`` will be encoded as such. This behavior is not JSON
408 specification compliant, but is consistent with most JavaScript based
409 encoders and decoders. Otherwise, it will be a :exc:`ValueError` to encode
410 such floats.
Brett Cannon4b964f92008-05-05 20:21:38 +0000411
Georg Brandl21946af2010-10-06 09:28:45 +0000412 If *sort_keys* is ``True`` (default ``False``), then the output of dictionaries
Brett Cannon4b964f92008-05-05 20:21:38 +0000413 will be sorted by key; this is useful for regression tests to ensure that
414 JSON serializations can be compared on a day-to-day basis.
415
Georg Brandl3961f182008-05-05 20:53:39 +0000416 If *indent* is a non-negative integer (it is ``None`` by default), then JSON
Brett Cannon4b964f92008-05-05 20:21:38 +0000417 array elements and object members will be pretty-printed with that indent
418 level. An indent level of 0 will only insert newlines. ``None`` is the most
419 compact representation.
420
Ezio Melotti3a237eb2012-11-29 00:22:30 +0200421 .. note::
422
423 Since the default item separator is ``', '``, the output might include
424 trailing whitespace when *indent* is specified. You can use
425 ``separators=(',', ': ')`` to avoid this.
426
Georg Brandl3961f182008-05-05 20:53:39 +0000427 If specified, *separators* should be an ``(item_separator, key_separator)``
428 tuple. The default is ``(', ', ': ')``. To get the most compact JSON
Brett Cannon4b964f92008-05-05 20:21:38 +0000429 representation, you should specify ``(',', ':')`` to eliminate whitespace.
430
431 If specified, *default* is a function that gets called for objects that can't
432 otherwise be serialized. It should return a JSON encodable version of the
433 object or raise a :exc:`TypeError`.
434
435 If *encoding* is not ``None``, then all input strings will be transformed
436 into unicode using that encoding prior to JSON-encoding. The default is
437 UTF-8.
438
439
440 .. method:: default(o)
441
442 Implement this method in a subclass such that it returns a serializable
443 object for *o*, or calls the base implementation (to raise a
444 :exc:`TypeError`).
445
446 For example, to support arbitrary iterators, you could implement default
447 like this::
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000448
Brett Cannon4b964f92008-05-05 20:21:38 +0000449 def default(self, o):
450 try:
Georg Brandl1379ae02008-09-24 09:47:55 +0000451 iterable = iter(o)
Brett Cannon4b964f92008-05-05 20:21:38 +0000452 except TypeError:
Georg Brandl1379ae02008-09-24 09:47:55 +0000453 pass
Brett Cannon4b964f92008-05-05 20:21:38 +0000454 else:
455 return list(iterable)
R David Murray35893b72013-03-17 22:06:18 -0400456 # Let the base class default method raise the TypeError
Brett Cannon4b964f92008-05-05 20:21:38 +0000457 return JSONEncoder.default(self, o)
458
459
460 .. method:: encode(o)
461
Georg Brandl3961f182008-05-05 20:53:39 +0000462 Return a JSON string representation of a Python data structure, *o*. For
Brett Cannon4b964f92008-05-05 20:21:38 +0000463 example::
464
465 >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
466 '{"foo": ["bar", "baz"]}'
467
468
469 .. method:: iterencode(o)
470
471 Encode the given object, *o*, and yield each string representation as
Georg Brandl3961f182008-05-05 20:53:39 +0000472 available. For example::
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000473
Brett Cannon4b964f92008-05-05 20:21:38 +0000474 for chunk in JSONEncoder().iterencode(bigobject):
475 mysocket.write(chunk)
Antoine Pitrouf3e0a692012-08-24 19:46:17 +0200476
477
478Standard Compliance
479-------------------
480
481The JSON format is specified by :rfc:`4627`. This section details this
482module's level of compliance with the RFC. For simplicity,
483:class:`JSONEncoder` and :class:`JSONDecoder` subclasses, and parameters other
484than those explicitly mentioned, are not considered.
485
486This module does not comply with the RFC in a strict fashion, implementing some
487extensions that are valid JavaScript but not valid JSON. In particular:
488
489- Top-level non-object, non-array values are accepted and output;
490- Infinite and NaN number values are accepted and output;
491- Repeated names within an object are accepted, and only the value of the last
492 name-value pair is used.
493
494Since the RFC permits RFC-compliant parsers to accept input texts that are not
495RFC-compliant, this module's deserializer is technically RFC-compliant under
496default settings.
497
498Character Encodings
499^^^^^^^^^^^^^^^^^^^
500
501The RFC recommends that JSON be represented using either UTF-8, UTF-16, or
502UTF-32, with UTF-8 being the default. Accordingly, this module uses UTF-8 as
503the default for its *encoding* parameter.
504
505This module's deserializer only directly works with ASCII-compatible encodings;
506UTF-16, UTF-32, and other ASCII-incompatible encodings require the use of
507workarounds described in the documentation for the deserializer's *encoding*
508parameter.
509
510The RFC also non-normatively describes a limited encoding detection technique
511for JSON texts; this module's deserializer does not implement this or any other
512kind of encoding detection.
513
514As permitted, though not required, by the RFC, this module's serializer sets
515*ensure_ascii=True* by default, thus escaping the output so that the resulting
516strings only contain ASCII characters.
517
518
519Top-level Non-Object, Non-Array Values
520^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
521
522The RFC specifies that the top-level value of a JSON text must be either a
523JSON object or array (Python :class:`dict` or :class:`list`). This module's
524deserializer also accepts input texts consisting solely of a
525JSON null, boolean, number, or string value::
526
527 >>> just_a_json_string = '"spam and eggs"' # Not by itself a valid JSON text
528 >>> json.loads(just_a_json_string)
529 u'spam and eggs'
530
531This module itself does not include a way to request that such input texts be
532regarded as illegal. Likewise, this module's serializer also accepts single
533Python :data:`None`, :class:`bool`, numeric, and :class:`str`
534values as input and will generate output texts consisting solely of a top-level
535JSON null, boolean, number, or string value without raising an exception::
536
537 >>> neither_a_list_nor_a_dict = u"spam and eggs"
538 >>> json.dumps(neither_a_list_nor_a_dict) # The result is not a valid JSON text
539 '"spam and eggs"'
540
541This module's serializer does not itself include a way to enforce the
542aforementioned constraint.
543
544
545Infinite and NaN Number Values
546^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
547
548The RFC does not permit the representation of infinite or NaN number values.
549Despite that, by default, this module accepts and outputs ``Infinity``,
550``-Infinity``, and ``NaN`` as if they were valid JSON number literal values::
551
552 >>> # Neither of these calls raises an exception, but the results are not valid JSON
553 >>> json.dumps(float('-inf'))
554 '-Infinity'
555 >>> json.dumps(float('nan'))
556 'NaN'
557 >>> # Same when deserializing
558 >>> json.loads('-Infinity')
559 -inf
560 >>> json.loads('NaN')
561 nan
562
563In the serializer, the *allow_nan* parameter can be used to alter this
564behavior. In the deserializer, the *parse_constant* parameter can be used to
565alter this behavior.
566
567
568Repeated Names Within an Object
569^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
570
571The RFC specifies that the names within a JSON object should be unique, but
572does not specify how repeated names in JSON objects should be handled. By
573default, this module does not raise an exception; instead, it ignores all but
574the last name-value pair for a given name::
575
576 >>> weird_json = '{"x": 1, "x": 2, "x": 3}'
577 >>> json.loads(weird_json)
578 {u'x': 3}
579
580The *object_pairs_hook* parameter can be used to alter this behavior.