blob: 819c3392942147e01cb31a242eb9c33e523224bf [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 ...
Christian Heimes90540002008-05-08 14:29:10 +000085 >>> dumps(2 + 1j, cls=ComplexEncoder)
86 '[2.0, 1.0]'
87 >>> ComplexEncoder().encode(2 + 1j)
88 '[2.0, 1.0]'
89 >>> list(ComplexEncoder().iterencode(2 + 1j))
90 ['[', '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
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000115.. function:: dump(obj, fp[, skipkeys[, ensure_ascii[, check_circular[, allow_nan[, cls[, indent[, separators[, default[, **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
Georg Brandl639ce962009-04-11 18:18:16 +0000121 of a basic type (:class:`str`, :class:`unicode`, :class:`int`,
Christian Heimes90540002008-05-08 14:29:10 +0000122 :class:`float`, :class:`bool`, ``None``) will be skipped instead of raising a
123 :exc:`TypeError`.
124
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000125 The :mod:`json` module always produces :class:`str` objects, not
126 :class:`bytes` objects. Therefore, ``fp.write()`` must support :class:`str`
127 input.
128
Christian Heimes90540002008-05-08 14:29:10 +0000129
130 If *check_circular* is ``False`` (default: ``True``), then the circular
131 reference check for container types will be skipped and a circular reference
132 will result in an :exc:`OverflowError` (or worse).
133
134 If *allow_nan* is ``False`` (default: ``True``), then it will be a
135 :exc:`ValueError` to serialize out of range :class:`float` values (``nan``,
136 ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of
137 using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
138
139 If *indent* is a non-negative integer, then JSON array elements and object
140 members will be pretty-printed with that indent level. An indent level of 0
141 will only insert newlines. ``None`` (the default) selects the most compact
142 representation.
143
144 If *separators* is an ``(item_separator, dict_separator)`` tuple, then it
145 will be used instead of the default ``(', ', ': ')`` separators. ``(',',
146 ':')`` is the most compact JSON representation.
147
Christian Heimes90540002008-05-08 14:29:10 +0000148 *default(obj)* is a function that should return a serializable version of
149 *obj* or raise :exc:`TypeError`. The default simply raises :exc:`TypeError`.
150
Georg Brandl1f01deb2009-01-03 22:47:39 +0000151 To use a custom :class:`JSONEncoder` subclass (e.g. one that overrides the
Christian Heimes90540002008-05-08 14:29:10 +0000152 :meth:`default` method to serialize additional types), specify it with the
153 *cls* kwarg.
154
155
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000156.. function:: dumps(obj[, skipkeys[, ensure_ascii[, check_circular[, allow_nan[, cls[, indent[, separators[, default[, **kw]]]]]]]]]])
Christian Heimes90540002008-05-08 14:29:10 +0000157
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000158 Serialize *obj* to a JSON formatted :class:`str`. The arguments have the
159 same meaning as in :func:`dump`.
Christian Heimes90540002008-05-08 14:29:10 +0000160
161
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000162.. function:: load(fp[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Christian Heimes90540002008-05-08 14:29:10 +0000163
164 Deserialize *fp* (a ``.read()``-supporting file-like object containing a JSON
165 document) to a Python object.
166
Christian Heimes90540002008-05-08 14:29:10 +0000167 *object_hook* is an optional function that will be called with the result of
168 any object literal decode (a :class:`dict`). The return value of
169 *object_hook* will be used instead of the :class:`dict`. This feature can be used
170 to implement custom decoders (e.g. JSON-RPC class hinting).
171
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000172 *object_pairs_hook* is an optional function that will be called with the
173 result of any object literal decode with an ordered list of pairs. The
174 return value of *object_pairs_hook* will be used instead of the
175 :class:`dict`. This feature can be used to implement custom decoders that
176 rely on the order that the key and value pairs are decoded (for example,
177 :func:`collections.OrderedDict` will remember the order of insertion). If
178 *object_hook* is also defined, the *object_pairs_hook* takes priority.
179
180 .. versionchanged:: 3.1
Hirokazu Yamamotoae9eb5c2009-04-26 03:34:06 +0000181 Added support for *object_pairs_hook*.
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000182
Christian Heimes90540002008-05-08 14:29:10 +0000183 *parse_float*, if specified, will be called with the string of every JSON
184 float to be decoded. By default, this is equivalent to ``float(num_str)``.
185 This can be used to use another datatype or parser for JSON floats
186 (e.g. :class:`decimal.Decimal`).
187
188 *parse_int*, if specified, will be called with the string of every JSON int
189 to be decoded. By default, this is equivalent to ``int(num_str)``. This can
190 be used to use another datatype or parser for JSON integers
191 (e.g. :class:`float`).
192
193 *parse_constant*, if specified, will be called with one of the following
194 strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``, ``'null'``, ``'true'``,
195 ``'false'``. This can be used to raise an exception if invalid JSON numbers
196 are encountered.
197
198 To use a custom :class:`JSONDecoder` subclass, specify it with the ``cls``
199 kwarg. Additional keyword arguments will be passed to the constructor of the
200 class.
201
202
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000203.. function:: loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Christian Heimes90540002008-05-08 14:29:10 +0000204
205 Deserialize *s* (a :class:`str` or :class:`unicode` instance containing a JSON
206 document) to a Python object.
207
208 If *s* is a :class:`str` instance and is encoded with an ASCII based encoding
209 other than UTF-8 (e.g. latin-1), then an appropriate *encoding* name must be
210 specified. Encodings that are not ASCII based (such as UCS-2) are not
211 allowed and should be decoded to :class:`unicode` first.
212
213 The other arguments have the same meaning as in :func:`dump`.
214
215
216Encoders and decoders
217---------------------
218
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000219.. class:: JSONDecoder([encoding[, object_hook[, parse_float[, parse_int[, parse_constant[, strict[, object_pairs_hook]]]]]]])
Christian Heimes90540002008-05-08 14:29:10 +0000220
221 Simple JSON decoder.
222
223 Performs the following translations in decoding by default:
224
225 +---------------+-------------------+
226 | JSON | Python |
227 +===============+===================+
228 | object | dict |
229 +---------------+-------------------+
230 | array | list |
231 +---------------+-------------------+
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000232 | string | str |
Christian Heimes90540002008-05-08 14:29:10 +0000233 +---------------+-------------------+
Georg Brandl639ce962009-04-11 18:18:16 +0000234 | number (int) | int |
Christian Heimes90540002008-05-08 14:29:10 +0000235 +---------------+-------------------+
236 | number (real) | float |
237 +---------------+-------------------+
238 | true | True |
239 +---------------+-------------------+
240 | false | False |
241 +---------------+-------------------+
242 | null | None |
243 +---------------+-------------------+
244
245 It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their
246 corresponding ``float`` values, which is outside the JSON spec.
247
Christian Heimes90540002008-05-08 14:29:10 +0000248 *object_hook*, if specified, will be called with the result of every JSON
249 object decoded and its return value will be used in place of the given
250 :class:`dict`. This can be used to provide custom deserializations (e.g. to
251 support JSON-RPC class hinting).
252
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000253 *object_pairs_hook*, if specified will be called with the result of every
254 JSON object decoded with an ordered list of pairs. The return value of
255 *object_pairs_hook* will be used instead of the :class:`dict`. This
256 feature can be used to implement custom decoders that rely on the order
257 that the key and value pairs are decoded (for example,
258 :func:`collections.OrderedDict` will remember the order of insertion). If
259 *object_hook* is also defined, the *object_pairs_hook* takes priority.
260
261 .. versionchanged:: 3.1
Hirokazu Yamamotoae9eb5c2009-04-26 03:34:06 +0000262 Added support for *object_pairs_hook*.
Raymond Hettinger9b8d0692009-04-21 03:27:12 +0000263
Christian Heimes90540002008-05-08 14:29:10 +0000264 *parse_float*, if specified, will be called with the string of every JSON
265 float to be decoded. By default, this is equivalent to ``float(num_str)``.
266 This can be used to use another datatype or parser for JSON floats
267 (e.g. :class:`decimal.Decimal`).
268
269 *parse_int*, if specified, will be called with the string of every JSON int
270 to be decoded. By default, this is equivalent to ``int(num_str)``. This can
271 be used to use another datatype or parser for JSON integers
272 (e.g. :class:`float`).
273
274 *parse_constant*, if specified, will be called with one of the following
275 strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``, ``'null'``, ``'true'``,
276 ``'false'``. This can be used to raise an exception if invalid JSON numbers
277 are encountered.
278
279
280 .. method:: decode(s)
281
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000282 Return the Python representation of *s* (a :class:`str` instance
283 containing a JSON document)
Christian Heimes90540002008-05-08 14:29:10 +0000284
285 .. method:: raw_decode(s)
286
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000287 Decode a JSON document from *s* (a :class:`str` beginning with a
288 JSON document) and return a 2-tuple of the Python representation
289 and the index in *s* where the document ended.
Christian Heimes90540002008-05-08 14:29:10 +0000290
291 This can be used to decode a JSON document from a string that may have
292 extraneous data at the end.
293
294
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000295.. class:: JSONEncoder([skipkeys[, ensure_ascii[, check_circular[, allow_nan[, sort_keys[, indent[, separators[, default]]]]]]]])
Christian Heimes90540002008-05-08 14:29:10 +0000296
297 Extensible JSON encoder for Python data structures.
298
299 Supports the following objects and types by default:
300
301 +-------------------+---------------+
302 | Python | JSON |
303 +===================+===============+
304 | dict | object |
305 +-------------------+---------------+
306 | list, tuple | array |
307 +-------------------+---------------+
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000308 | str | string |
Christian Heimes90540002008-05-08 14:29:10 +0000309 +-------------------+---------------+
Georg Brandl639ce962009-04-11 18:18:16 +0000310 | int, float | number |
Christian Heimes90540002008-05-08 14:29:10 +0000311 +-------------------+---------------+
312 | True | true |
313 +-------------------+---------------+
314 | False | false |
315 +-------------------+---------------+
316 | None | null |
317 +-------------------+---------------+
318
319 To extend this to recognize other objects, subclass and implement a
320 :meth:`default` method with another method that returns a serializable object
321 for ``o`` if possible, otherwise it should call the superclass implementation
322 (to raise :exc:`TypeError`).
323
324 If *skipkeys* is ``False`` (the default), then it is a :exc:`TypeError` to
Georg Brandl639ce962009-04-11 18:18:16 +0000325 attempt encoding of keys that are not str, int, float or None. If
Christian Heimes90540002008-05-08 14:29:10 +0000326 *skipkeys* is ``True``, such items are simply skipped.
327
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000328 If *ensure_ascii* is ``True`` (the default), the output is guaranteed to
329 have all incoming non-ASCII characters escaped. If *ensure_ascii* is
330 ``False``, these characters will be output as-is.
Christian Heimes90540002008-05-08 14:29:10 +0000331
332 If *check_circular* is ``True`` (the default), then lists, dicts, and custom
333 encoded objects will be checked for circular references during encoding to
334 prevent an infinite recursion (which would cause an :exc:`OverflowError`).
335 Otherwise, no such check takes place.
336
337 If *allow_nan* is ``True`` (the default), then ``NaN``, ``Infinity``, and
338 ``-Infinity`` will be encoded as such. This behavior is not JSON
339 specification compliant, but is consistent with most JavaScript based
340 encoders and decoders. Otherwise, it will be a :exc:`ValueError` to encode
341 such floats.
342
343 If *sort_keys* is ``True`` (the default), then the output of dictionaries
344 will be sorted by key; this is useful for regression tests to ensure that
345 JSON serializations can be compared on a day-to-day basis.
346
347 If *indent* is a non-negative integer (it is ``None`` by default), then JSON
348 array elements and object members will be pretty-printed with that indent
349 level. An indent level of 0 will only insert newlines. ``None`` is the most
350 compact representation.
351
352 If specified, *separators* should be an ``(item_separator, key_separator)``
353 tuple. The default is ``(', ', ': ')``. To get the most compact JSON
354 representation, you should specify ``(',', ':')`` to eliminate whitespace.
355
356 If specified, *default* is a function that gets called for objects that can't
357 otherwise be serialized. It should return a JSON encodable version of the
358 object or raise a :exc:`TypeError`.
359
Christian Heimes90540002008-05-08 14:29:10 +0000360
361 .. method:: default(o)
362
363 Implement this method in a subclass such that it returns a serializable
364 object for *o*, or calls the base implementation (to raise a
365 :exc:`TypeError`).
366
367 For example, to support arbitrary iterators, you could implement default
368 like this::
Georg Brandl48310cd2009-01-03 21:18:54 +0000369
Christian Heimes90540002008-05-08 14:29:10 +0000370 def default(self, o):
371 try:
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +0000372 iterable = iter(o)
Christian Heimes90540002008-05-08 14:29:10 +0000373 except TypeError:
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +0000374 pass
Christian Heimes90540002008-05-08 14:29:10 +0000375 else:
376 return list(iterable)
377 return JSONEncoder.default(self, o)
378
379
380 .. method:: encode(o)
381
382 Return a JSON string representation of a Python data structure, *o*. For
383 example::
384
385 >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
386 '{"foo": ["bar", "baz"]}'
387
388
389 .. method:: iterencode(o)
390
391 Encode the given object, *o*, and yield each string representation as
392 available. For example::
Georg Brandl48310cd2009-01-03 21:18:54 +0000393
Christian Heimes90540002008-05-08 14:29:10 +0000394 for chunk in JSONEncoder().iterencode(bigobject):
395 mysocket.write(chunk)