blob: 2bf242fff42ba25ce99ba506bf7b17e920b495bc [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
9JSON (JavaScript Object Notation) <http://json.org> is a subset of JavaScript
10syntax (ECMA-262 3rd edition) used as a lightweight data interchange format.
11
12:mod:`json` exposes an API familiar to users of the standard library
13:mod:`marshal` and :mod:`pickle` modules.
14
15Encoding basic Python object hierarchies::
Georg Brandl48310cd2009-01-03 21:18:54 +000016
Christian Heimes90540002008-05-08 14:29:10 +000017 >>> import json
18 >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
19 '["foo", {"bar": ["baz", null, 1.0, 2]}]'
Neal Norwitz752abd02008-05-13 04:55:24 +000020 >>> print(json.dumps("\"foo\bar"))
Christian Heimes90540002008-05-08 14:29:10 +000021 "\"foo\bar"
Benjamin Peterson2505bc62008-05-15 02:17:58 +000022 >>> print(json.dumps('\u1234'))
Christian Heimes90540002008-05-08 14:29:10 +000023 "\u1234"
Neal Norwitz752abd02008-05-13 04:55:24 +000024 >>> print(json.dumps('\\'))
Christian Heimes90540002008-05-08 14:29:10 +000025 "\\"
Neal Norwitz752abd02008-05-13 04:55:24 +000026 >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
Christian Heimes90540002008-05-08 14:29:10 +000027 {"a": 0, "b": 0, "c": 0}
Benjamin Peterson2505bc62008-05-15 02:17:58 +000028 >>> from io import StringIO
Christian Heimes90540002008-05-08 14:29:10 +000029 >>> io = StringIO()
30 >>> json.dump(['streaming API'], io)
31 >>> io.getvalue()
32 '["streaming API"]'
33
34Compact encoding::
35
36 >>> import json
37 >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
38 '[1,2,3,{"4":5,"6":7}]'
39
40Pretty printing::
41
42 >>> import json
Neal Norwitz752abd02008-05-13 04:55:24 +000043 >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
Christian Heimes90540002008-05-08 14:29:10 +000044 {
Georg Brandl48310cd2009-01-03 21:18:54 +000045 "4": 5,
Christian Heimes90540002008-05-08 14:29:10 +000046 "6": 7
47 }
48
49Decoding JSON::
Georg Brandl48310cd2009-01-03 21:18:54 +000050
Christian Heimes90540002008-05-08 14:29:10 +000051 >>> import json
52 >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
Benjamin Peterson2505bc62008-05-15 02:17:58 +000053 ['foo', {'bar': ['baz', None, 1.0, 2]}]
Christian Heimes90540002008-05-08 14:29:10 +000054 >>> json.loads('"\\"foo\\bar"')
Benjamin Peterson2505bc62008-05-15 02:17:58 +000055 '"foo\x08ar'
56 >>> from io import StringIO
Christian Heimes90540002008-05-08 14:29:10 +000057 >>> io = StringIO('["streaming API"]')
58 >>> json.load(io)
Benjamin Peterson2505bc62008-05-15 02:17:58 +000059 ['streaming API']
Christian Heimes90540002008-05-08 14:29:10 +000060
61Specializing JSON object decoding::
62
63 >>> import json
64 >>> def as_complex(dct):
65 ... if '__complex__' in dct:
66 ... return complex(dct['real'], dct['imag'])
67 ... return dct
Benjamin Peterson2505bc62008-05-15 02:17:58 +000068 ...
Christian Heimes90540002008-05-08 14:29:10 +000069 >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
70 ... object_hook=as_complex)
71 (1+2j)
72 >>> import decimal
73 >>> json.loads('1.1', parse_float=decimal.Decimal)
74 Decimal('1.1')
75
76Extending :class:`JSONEncoder`::
Georg Brandl48310cd2009-01-03 21:18:54 +000077
Christian Heimes90540002008-05-08 14:29:10 +000078 >>> import json
79 >>> class ComplexEncoder(json.JSONEncoder):
80 ... def default(self, obj):
81 ... if isinstance(obj, complex):
82 ... return [obj.real, obj.imag]
83 ... return json.JSONEncoder.default(self, obj)
Benjamin Peterson2505bc62008-05-15 02:17:58 +000084 ...
Georg Brandl57a5e3f2010-10-06 08:54:16 +000085 >>> json.dumps(2 + 1j, cls=ComplexEncoder)
Christian Heimes90540002008-05-08 14:29:10 +000086 '[2.0, 1.0]'
87 >>> ComplexEncoder().encode(2 + 1j)
88 '[2.0, 1.0]'
89 >>> list(ComplexEncoder().iterencode(2 + 1j))
Georg Brandl57a5e3f2010-10-06 08:54:16 +000090 ['[2.0', ', 1.0', ']']
Georg Brandl48310cd2009-01-03 21:18:54 +000091
Christian Heimes90540002008-05-08 14:29:10 +000092
93.. highlight:: none
94
95Using json.tool from the shell to validate and pretty-print::
Georg Brandl48310cd2009-01-03 21:18:54 +000096
Christian Heimes90540002008-05-08 14:29:10 +000097 $ echo '{"json":"obj"}' | python -mjson.tool
98 {
99 "json": "obj"
100 }
101 $ echo '{ 1.2:3.4}' | python -mjson.tool
102 Expecting property name: line 1 column 2 (char 2)
103
104.. highlight:: python
105
Georg Brandl48310cd2009-01-03 21:18:54 +0000106.. note::
Christian Heimes90540002008-05-08 14:29:10 +0000107
108 The JSON produced by this module's default settings is a subset of
109 YAML, so it may be used as a serializer for that as well.
110
111
112Basic Usage
113-----------
114
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000115.. function:: dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, **kw)
Christian Heimes90540002008-05-08 14:29:10 +0000116
117 Serialize *obj* as a JSON formatted stream to *fp* (a ``.write()``-supporting
118 file-like object).
119
120 If *skipkeys* is ``True`` (default: ``False``), then dict keys that are not
Antoine Pitroua970e622011-01-21 21:39:56 +0000121 of a basic type (:class:`str`, :class:`int`, :class:`float`, :class:`bool`,
122 ``None``) will be skipped instead of raising a :exc:`TypeError`.
Christian Heimes90540002008-05-08 14:29:10 +0000123
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000124 The :mod:`json` module always produces :class:`str` objects, not
125 :class:`bytes` objects. Therefore, ``fp.write()`` must support :class:`str`
126 input.
127
Christian Heimes90540002008-05-08 14:29:10 +0000128 If *check_circular* is ``False`` (default: ``True``), then the circular
129 reference check for container types will be skipped and a circular reference
130 will result in an :exc:`OverflowError` (or worse).
131
132 If *allow_nan* is ``False`` (default: ``True``), then it will be a
133 :exc:`ValueError` to serialize out of range :class:`float` values (``nan``,
134 ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of
135 using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
136
137 If *indent* is a non-negative integer, then JSON array elements and object
R David Murray3dd02d62011-04-12 21:02:45 -0400138 members will be pretty-printed with that indent level. An indent level of 0,
139 or negative, will only insert newlines. ``None`` (the default) selects the
140 most compact representation.
Christian Heimes90540002008-05-08 14:29:10 +0000141
142 If *separators* is an ``(item_separator, dict_separator)`` tuple, then it
143 will be used instead of the default ``(', ', ': ')`` separators. ``(',',
144 ':')`` is the most compact JSON representation.
145
Christian Heimes90540002008-05-08 14:29:10 +0000146 *default(obj)* is a function that should return a serializable version of
147 *obj* or raise :exc:`TypeError`. The default simply raises :exc:`TypeError`.
148
Georg Brandl1f01deb2009-01-03 22:47:39 +0000149 To use a custom :class:`JSONEncoder` subclass (e.g. one that overrides the
Christian Heimes90540002008-05-08 14:29:10 +0000150 :meth:`default` method to serialize additional types), specify it with the
Georg Brandlc524cff2010-11-26 08:42:45 +0000151 *cls* kwarg; otherwise :class:`JSONEncoder` is used.
Christian Heimes90540002008-05-08 14:29:10 +0000152
153
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000154.. function:: dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, **kw)
Christian Heimes90540002008-05-08 14:29:10 +0000155
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000156 Serialize *obj* to a JSON formatted :class:`str`. The arguments have the
157 same meaning as in :func:`dump`.
Christian Heimes90540002008-05-08 14:29:10 +0000158
159
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000160.. 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 +0000161
162 Deserialize *fp* (a ``.read()``-supporting file-like object containing a JSON
163 document) to a Python object.
164
Christian Heimes90540002008-05-08 14:29:10 +0000165 *object_hook* is an optional function that will be called with the result of
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000166 any object literal decoded (a :class:`dict`). The return value of
Christian Heimes90540002008-05-08 14:29:10 +0000167 *object_hook* will be used instead of the :class:`dict`. This feature can be used
168 to implement custom decoders (e.g. JSON-RPC class hinting).
169
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000170 *object_pairs_hook* is an optional function that will be called with the
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000171 result of any object literal decoded with an ordered list of pairs. The
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000172 return value of *object_pairs_hook* will be used instead of the
173 :class:`dict`. This feature can be used to implement custom decoders that
174 rely on the order that the key and value pairs are decoded (for example,
175 :func:`collections.OrderedDict` will remember the order of insertion). If
176 *object_hook* is also defined, the *object_pairs_hook* takes priority.
177
178 .. versionchanged:: 3.1
Hirokazu Yamamotoae9eb5c2009-04-26 03:34:06 +0000179 Added support for *object_pairs_hook*.
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000180
Christian Heimes90540002008-05-08 14:29:10 +0000181 *parse_float*, if specified, will be called with the string of every JSON
182 float to be decoded. By default, this is equivalent to ``float(num_str)``.
183 This can be used to use another datatype or parser for JSON floats
184 (e.g. :class:`decimal.Decimal`).
185
186 *parse_int*, if specified, will be called with the string of every JSON int
187 to be decoded. By default, this is equivalent to ``int(num_str)``. This can
188 be used to use another datatype or parser for JSON integers
189 (e.g. :class:`float`).
190
191 *parse_constant*, if specified, will be called with one of the following
192 strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``, ``'null'``, ``'true'``,
193 ``'false'``. This can be used to raise an exception if invalid JSON numbers
194 are encountered.
195
196 To use a custom :class:`JSONDecoder` subclass, specify it with the ``cls``
Georg Brandlc524cff2010-11-26 08:42:45 +0000197 kwarg; otherwise :class:`JSONDecoder` is used. Additional keyword arguments
198 will be passed to the constructor of the class.
Christian Heimes90540002008-05-08 14:29:10 +0000199
200
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000201.. 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 +0000202
Antoine Pitroua970e622011-01-21 21:39:56 +0000203 Deserialize *s* (a :class:`str` instance containing a JSON document) to a
204 Python object.
Christian Heimes90540002008-05-08 14:29:10 +0000205
Antoine Pitroua970e622011-01-21 21:39:56 +0000206 The other arguments have the same meaning as in :func:`load`, except
207 *encoding* which is ignored and deprecated.
Christian Heimes90540002008-05-08 14:29:10 +0000208
209
210Encoders and decoders
211---------------------
212
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000213.. 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 +0000214
215 Simple JSON decoder.
216
217 Performs the following translations in decoding by default:
218
219 +---------------+-------------------+
220 | JSON | Python |
221 +===============+===================+
222 | object | dict |
223 +---------------+-------------------+
224 | array | list |
225 +---------------+-------------------+
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000226 | string | str |
Christian Heimes90540002008-05-08 14:29:10 +0000227 +---------------+-------------------+
Georg Brandl639ce962009-04-11 18:18:16 +0000228 | number (int) | int |
Christian Heimes90540002008-05-08 14:29:10 +0000229 +---------------+-------------------+
230 | number (real) | float |
231 +---------------+-------------------+
232 | true | True |
233 +---------------+-------------------+
234 | false | False |
235 +---------------+-------------------+
236 | null | None |
237 +---------------+-------------------+
238
239 It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their
240 corresponding ``float`` values, which is outside the JSON spec.
241
Christian Heimes90540002008-05-08 14:29:10 +0000242 *object_hook*, if specified, will be called with the result of every JSON
243 object decoded and its return value will be used in place of the given
244 :class:`dict`. This can be used to provide custom deserializations (e.g. to
245 support JSON-RPC class hinting).
246
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000247 *object_pairs_hook*, if specified will be called with the result of every
248 JSON object decoded with an ordered list of pairs. The return value of
249 *object_pairs_hook* will be used instead of the :class:`dict`. This
250 feature can be used to implement custom decoders that rely on the order
251 that the key and value pairs are decoded (for example,
252 :func:`collections.OrderedDict` will remember the order of insertion). If
253 *object_hook* is also defined, the *object_pairs_hook* takes priority.
254
255 .. versionchanged:: 3.1
Hirokazu Yamamotoae9eb5c2009-04-26 03:34:06 +0000256 Added support for *object_pairs_hook*.
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000257
Christian Heimes90540002008-05-08 14:29:10 +0000258 *parse_float*, if specified, will be called with the string of every JSON
259 float to be decoded. By default, this is equivalent to ``float(num_str)``.
260 This can be used to use another datatype or parser for JSON floats
261 (e.g. :class:`decimal.Decimal`).
262
263 *parse_int*, if specified, will be called with the string of every JSON int
264 to be decoded. By default, this is equivalent to ``int(num_str)``. This can
265 be used to use another datatype or parser for JSON integers
266 (e.g. :class:`float`).
267
268 *parse_constant*, if specified, will be called with one of the following
269 strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``, ``'null'``, ``'true'``,
270 ``'false'``. This can be used to raise an exception if invalid JSON numbers
271 are encountered.
272
Georg Brandlc524cff2010-11-26 08:42:45 +0000273 If *strict* is ``False`` (``True`` is the default), then control characters
274 will be allowed inside strings. Control characters in this context are
275 those with character codes in the 0-31 range, including ``'\t'`` (tab),
276 ``'\n'``, ``'\r'`` and ``'\0'``.
277
Christian Heimes90540002008-05-08 14:29:10 +0000278
279 .. method:: decode(s)
280
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000281 Return the Python representation of *s* (a :class:`str` instance
282 containing a JSON document)
Christian Heimes90540002008-05-08 14:29:10 +0000283
284 .. method:: raw_decode(s)
285
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000286 Decode a JSON document from *s* (a :class:`str` beginning with a
287 JSON document) and return a 2-tuple of the Python representation
288 and the index in *s* where the document ended.
Christian Heimes90540002008-05-08 14:29:10 +0000289
290 This can be used to decode a JSON document from a string that may have
291 extraneous data at the end.
292
293
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000294.. 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 +0000295
296 Extensible JSON encoder for Python data structures.
297
298 Supports the following objects and types by default:
299
300 +-------------------+---------------+
301 | Python | JSON |
302 +===================+===============+
303 | dict | object |
304 +-------------------+---------------+
305 | list, tuple | array |
306 +-------------------+---------------+
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000307 | str | string |
Christian Heimes90540002008-05-08 14:29:10 +0000308 +-------------------+---------------+
Georg Brandl639ce962009-04-11 18:18:16 +0000309 | int, float | number |
Christian Heimes90540002008-05-08 14:29:10 +0000310 +-------------------+---------------+
311 | True | true |
312 +-------------------+---------------+
313 | False | false |
314 +-------------------+---------------+
315 | None | null |
316 +-------------------+---------------+
317
318 To extend this to recognize other objects, subclass and implement a
319 :meth:`default` method with another method that returns a serializable object
320 for ``o`` if possible, otherwise it should call the superclass implementation
321 (to raise :exc:`TypeError`).
322
323 If *skipkeys* is ``False`` (the default), then it is a :exc:`TypeError` to
Georg Brandl639ce962009-04-11 18:18:16 +0000324 attempt encoding of keys that are not str, int, float or None. If
Christian Heimes90540002008-05-08 14:29:10 +0000325 *skipkeys* is ``True``, such items are simply skipped.
326
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000327 If *ensure_ascii* is ``True`` (the default), the output is guaranteed to
328 have all incoming non-ASCII characters escaped. If *ensure_ascii* is
329 ``False``, these characters will be output as-is.
Christian Heimes90540002008-05-08 14:29:10 +0000330
331 If *check_circular* is ``True`` (the default), then lists, dicts, and custom
332 encoded objects will be checked for circular references during encoding to
333 prevent an infinite recursion (which would cause an :exc:`OverflowError`).
334 Otherwise, no such check takes place.
335
336 If *allow_nan* is ``True`` (the default), then ``NaN``, ``Infinity``, and
337 ``-Infinity`` will be encoded as such. This behavior is not JSON
338 specification compliant, but is consistent with most JavaScript based
339 encoders and decoders. Otherwise, it will be a :exc:`ValueError` to encode
340 such floats.
341
Georg Brandl57a5e3f2010-10-06 08:54:16 +0000342 If *sort_keys* is ``True`` (default ``False``), then the output of dictionaries
Christian Heimes90540002008-05-08 14:29:10 +0000343 will be sorted by key; this is useful for regression tests to ensure that
344 JSON serializations can be compared on a day-to-day basis.
345
346 If *indent* is a non-negative integer (it is ``None`` by default), then JSON
347 array elements and object members will be pretty-printed with that indent
348 level. An indent level of 0 will only insert newlines. ``None`` is the most
349 compact representation.
350
351 If specified, *separators* should be an ``(item_separator, key_separator)``
352 tuple. The default is ``(', ', ': ')``. To get the most compact JSON
353 representation, you should specify ``(',', ':')`` to eliminate whitespace.
354
355 If specified, *default* is a function that gets called for objects that can't
356 otherwise be serialized. It should return a JSON encodable version of the
357 object or raise a :exc:`TypeError`.
358
Christian Heimes90540002008-05-08 14:29:10 +0000359
360 .. method:: default(o)
361
362 Implement this method in a subclass such that it returns a serializable
363 object for *o*, or calls the base implementation (to raise a
364 :exc:`TypeError`).
365
366 For example, to support arbitrary iterators, you could implement default
367 like this::
Georg Brandl48310cd2009-01-03 21:18:54 +0000368
Christian Heimes90540002008-05-08 14:29:10 +0000369 def default(self, o):
370 try:
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +0000371 iterable = iter(o)
Christian Heimes90540002008-05-08 14:29:10 +0000372 except TypeError:
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +0000373 pass
Christian Heimes90540002008-05-08 14:29:10 +0000374 else:
375 return list(iterable)
Georg Brandl57a5e3f2010-10-06 08:54:16 +0000376 return json.JSONEncoder.default(self, o)
Christian Heimes90540002008-05-08 14:29:10 +0000377
378
379 .. method:: encode(o)
380
381 Return a JSON string representation of a Python data structure, *o*. For
382 example::
383
Georg Brandl57a5e3f2010-10-06 08:54:16 +0000384 >>> json.JSONEncoder().encode({"foo": ["bar", "baz"]})
Christian Heimes90540002008-05-08 14:29:10 +0000385 '{"foo": ["bar", "baz"]}'
386
387
388 .. method:: iterencode(o)
389
390 Encode the given object, *o*, and yield each string representation as
391 available. For example::
Georg Brandl48310cd2009-01-03 21:18:54 +0000392
Georg Brandl57a5e3f2010-10-06 08:54:16 +0000393 for chunk in json.JSONEncoder().iterencode(bigobject):
Christian Heimes90540002008-05-08 14:29:10 +0000394 mysocket.write(chunk)