Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 1 | :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 Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 8 | |
| 9 | JSON (JavaScript Object Notation) <http://json.org> is a subset of JavaScript |
| 10 | syntax (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 | |
| 15 | Encoding basic Python object hierarchies:: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 16 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 17 | >>> import json |
| 18 | >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) |
| 19 | '["foo", {"bar": ["baz", null, 1.0, 2]}]' |
Neal Norwitz | 752abd0 | 2008-05-13 04:55:24 +0000 | [diff] [blame] | 20 | >>> print(json.dumps("\"foo\bar")) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 21 | "\"foo\bar" |
Benjamin Peterson | 2505bc6 | 2008-05-15 02:17:58 +0000 | [diff] [blame] | 22 | >>> print(json.dumps('\u1234')) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 23 | "\u1234" |
Neal Norwitz | 752abd0 | 2008-05-13 04:55:24 +0000 | [diff] [blame] | 24 | >>> print(json.dumps('\\')) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 25 | "\\" |
Neal Norwitz | 752abd0 | 2008-05-13 04:55:24 +0000 | [diff] [blame] | 26 | >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 27 | {"a": 0, "b": 0, "c": 0} |
Benjamin Peterson | 2505bc6 | 2008-05-15 02:17:58 +0000 | [diff] [blame] | 28 | >>> from io import StringIO |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 29 | >>> io = StringIO() |
| 30 | >>> json.dump(['streaming API'], io) |
| 31 | >>> io.getvalue() |
| 32 | '["streaming API"]' |
| 33 | |
| 34 | Compact 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 | |
| 40 | Pretty printing:: |
| 41 | |
| 42 | >>> import json |
Neal Norwitz | 752abd0 | 2008-05-13 04:55:24 +0000 | [diff] [blame] | 43 | >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 44 | { |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 45 | "4": 5, |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 46 | "6": 7 |
| 47 | } |
| 48 | |
| 49 | Decoding JSON:: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 50 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 51 | >>> import json |
| 52 | >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') |
Benjamin Peterson | 2505bc6 | 2008-05-15 02:17:58 +0000 | [diff] [blame] | 53 | ['foo', {'bar': ['baz', None, 1.0, 2]}] |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 54 | >>> json.loads('"\\"foo\\bar"') |
Benjamin Peterson | 2505bc6 | 2008-05-15 02:17:58 +0000 | [diff] [blame] | 55 | '"foo\x08ar' |
| 56 | >>> from io import StringIO |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 57 | >>> io = StringIO('["streaming API"]') |
| 58 | >>> json.load(io) |
Benjamin Peterson | 2505bc6 | 2008-05-15 02:17:58 +0000 | [diff] [blame] | 59 | ['streaming API'] |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 60 | |
| 61 | Specializing 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 Peterson | 2505bc6 | 2008-05-15 02:17:58 +0000 | [diff] [blame] | 68 | ... |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 69 | >>> 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 | |
| 76 | Extending :class:`JSONEncoder`:: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 77 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 78 | >>> 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 Peterson | 2505bc6 | 2008-05-15 02:17:58 +0000 | [diff] [blame] | 84 | ... |
Georg Brandl | 0bb73b8 | 2010-09-03 22:36:22 +0000 | [diff] [blame] | 85 | >>> json.dumps(2 + 1j, cls=ComplexEncoder) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 86 | '[2.0, 1.0]' |
| 87 | >>> ComplexEncoder().encode(2 + 1j) |
| 88 | '[2.0, 1.0]' |
| 89 | >>> list(ComplexEncoder().iterencode(2 + 1j)) |
Georg Brandl | 0bb73b8 | 2010-09-03 22:36:22 +0000 | [diff] [blame] | 90 | ['[2.0', ', 1.0', ']'] |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 91 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 92 | |
| 93 | .. highlight:: none |
| 94 | |
| 95 | Using json.tool from the shell to validate and pretty-print:: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 96 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 97 | $ 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 Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 106 | .. note:: |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 107 | |
| 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 | |
| 112 | Basic Usage |
| 113 | ----------- |
| 114 | |
Georg Brandl | cd7f32b | 2009-06-08 09:13:45 +0000 | [diff] [blame] | 115 | .. 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 Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 116 | |
| 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 |
Ezio Melotti | 985e24d | 2009-09-13 07:54:02 +0000 | [diff] [blame] | 121 | of a basic type (:class:`bytes`, :class:`str`, :class:`int`, |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 122 | :class:`float`, :class:`bool`, ``None``) will be skipped instead of raising a |
| 123 | :exc:`TypeError`. |
| 124 | |
Benjamin Peterson | c6b607d | 2009-05-02 12:36:44 +0000 | [diff] [blame] | 125 | 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 Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 129 | If *check_circular* is ``False`` (default: ``True``), then the circular |
| 130 | reference check for container types will be skipped and a circular reference |
| 131 | will result in an :exc:`OverflowError` (or worse). |
| 132 | |
| 133 | If *allow_nan* is ``False`` (default: ``True``), then it will be a |
| 134 | :exc:`ValueError` to serialize out of range :class:`float` values (``nan``, |
| 135 | ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of |
| 136 | using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). |
| 137 | |
Raymond Hettinger | b643ef8 | 2010-10-31 08:00:16 +0000 | [diff] [blame] | 138 | If *indent* is a non-negative integer or string, then JSON array elements and |
| 139 | object members will be pretty-printed with that indent level. An indent level |
| 140 | of 0 or ``""`` will only insert newlines. ``None`` (the default) selects the |
| 141 | most compact representation. Using an integer indent indents that many spaces |
| 142 | per level. If *indent* is a string (such at '\t'), that string is used to indent |
| 143 | each level. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 144 | |
| 145 | If *separators* is an ``(item_separator, dict_separator)`` tuple, then it |
| 146 | will be used instead of the default ``(', ', ': ')`` separators. ``(',', |
| 147 | ':')`` is the most compact JSON representation. |
| 148 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 149 | *default(obj)* is a function that should return a serializable version of |
| 150 | *obj* or raise :exc:`TypeError`. The default simply raises :exc:`TypeError`. |
| 151 | |
Georg Brandl | 1f01deb | 2009-01-03 22:47:39 +0000 | [diff] [blame] | 152 | To use a custom :class:`JSONEncoder` subclass (e.g. one that overrides the |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 153 | :meth:`default` method to serialize additional types), specify it with the |
Georg Brandl | d4460aa | 2010-10-15 17:03:02 +0000 | [diff] [blame] | 154 | *cls* kwarg; otherwise :class:`JSONEncoder` is used. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 155 | |
| 156 | |
Georg Brandl | cd7f32b | 2009-06-08 09:13:45 +0000 | [diff] [blame] | 157 | .. function:: dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, **kw) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 158 | |
Benjamin Peterson | c6b607d | 2009-05-02 12:36:44 +0000 | [diff] [blame] | 159 | Serialize *obj* to a JSON formatted :class:`str`. The arguments have the |
| 160 | same meaning as in :func:`dump`. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 161 | |
| 162 | |
Georg Brandl | cd7f32b | 2009-06-08 09:13:45 +0000 | [diff] [blame] | 163 | .. function:: load(fp, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 164 | |
| 165 | Deserialize *fp* (a ``.read()``-supporting file-like object containing a JSON |
| 166 | document) to a Python object. |
| 167 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 168 | *object_hook* is an optional function that will be called with the result of |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 169 | any object literal decoded (a :class:`dict`). The return value of |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 170 | *object_hook* will be used instead of the :class:`dict`. This feature can be used |
| 171 | to implement custom decoders (e.g. JSON-RPC class hinting). |
| 172 | |
Raymond Hettinger | 9b8d069 | 2009-04-21 03:27:12 +0000 | [diff] [blame] | 173 | *object_pairs_hook* is an optional function that will be called with the |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 174 | result of any object literal decoded with an ordered list of pairs. The |
Raymond Hettinger | 9b8d069 | 2009-04-21 03:27:12 +0000 | [diff] [blame] | 175 | return value of *object_pairs_hook* will be used instead of the |
| 176 | :class:`dict`. This feature can be used to implement custom decoders that |
| 177 | rely on the order that the key and value pairs are decoded (for example, |
| 178 | :func:`collections.OrderedDict` will remember the order of insertion). If |
| 179 | *object_hook* is also defined, the *object_pairs_hook* takes priority. |
| 180 | |
| 181 | .. versionchanged:: 3.1 |
Hirokazu Yamamoto | ae9eb5c | 2009-04-26 03:34:06 +0000 | [diff] [blame] | 182 | Added support for *object_pairs_hook*. |
Raymond Hettinger | 9b8d069 | 2009-04-21 03:27:12 +0000 | [diff] [blame] | 183 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 184 | *parse_float*, if specified, will be called with the string of every JSON |
| 185 | float to be decoded. By default, this is equivalent to ``float(num_str)``. |
| 186 | This can be used to use another datatype or parser for JSON floats |
| 187 | (e.g. :class:`decimal.Decimal`). |
| 188 | |
| 189 | *parse_int*, if specified, will be called with the string of every JSON int |
| 190 | to be decoded. By default, this is equivalent to ``int(num_str)``. This can |
| 191 | be used to use another datatype or parser for JSON integers |
| 192 | (e.g. :class:`float`). |
| 193 | |
| 194 | *parse_constant*, if specified, will be called with one of the following |
| 195 | strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``, ``'null'``, ``'true'``, |
| 196 | ``'false'``. This can be used to raise an exception if invalid JSON numbers |
| 197 | are encountered. |
| 198 | |
| 199 | To use a custom :class:`JSONDecoder` subclass, specify it with the ``cls`` |
Georg Brandl | d4460aa | 2010-10-15 17:03:02 +0000 | [diff] [blame] | 200 | kwarg; otherwise :class:`JSONDecoder` is used. Additional keyword arguments |
| 201 | will be passed to the constructor of the class. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 202 | |
| 203 | |
Georg Brandl | cd7f32b | 2009-06-08 09:13:45 +0000 | [diff] [blame] | 204 | .. 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 Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 205 | |
Ezio Melotti | 985e24d | 2009-09-13 07:54:02 +0000 | [diff] [blame] | 206 | Deserialize *s* (a :class:`bytes` or :class:`str` instance containing a JSON |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 207 | document) to a Python object. |
| 208 | |
Ezio Melotti | 985e24d | 2009-09-13 07:54:02 +0000 | [diff] [blame] | 209 | If *s* is a :class:`bytes` instance and is encoded with an ASCII based encoding |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 210 | other than UTF-8 (e.g. latin-1), then an appropriate *encoding* name must be |
| 211 | specified. Encodings that are not ASCII based (such as UCS-2) are not |
Ezio Melotti | 985e24d | 2009-09-13 07:54:02 +0000 | [diff] [blame] | 212 | allowed and should be decoded to :class:`str` first. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 213 | |
Georg Brandl | 8569e58 | 2010-05-19 20:57:08 +0000 | [diff] [blame] | 214 | The other arguments have the same meaning as in :func:`load`. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 215 | |
| 216 | |
| 217 | Encoders and decoders |
| 218 | --------------------- |
| 219 | |
Georg Brandl | cd7f32b | 2009-06-08 09:13:45 +0000 | [diff] [blame] | 220 | .. class:: JSONDecoder(object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 221 | |
| 222 | Simple JSON decoder. |
| 223 | |
| 224 | Performs the following translations in decoding by default: |
| 225 | |
| 226 | +---------------+-------------------+ |
| 227 | | JSON | Python | |
| 228 | +===============+===================+ |
| 229 | | object | dict | |
| 230 | +---------------+-------------------+ |
| 231 | | array | list | |
| 232 | +---------------+-------------------+ |
Benjamin Peterson | c6b607d | 2009-05-02 12:36:44 +0000 | [diff] [blame] | 233 | | string | str | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 234 | +---------------+-------------------+ |
Georg Brandl | 639ce96 | 2009-04-11 18:18:16 +0000 | [diff] [blame] | 235 | | number (int) | int | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 236 | +---------------+-------------------+ |
| 237 | | number (real) | float | |
| 238 | +---------------+-------------------+ |
| 239 | | true | True | |
| 240 | +---------------+-------------------+ |
| 241 | | false | False | |
| 242 | +---------------+-------------------+ |
| 243 | | null | None | |
| 244 | +---------------+-------------------+ |
| 245 | |
| 246 | It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their |
| 247 | corresponding ``float`` values, which is outside the JSON spec. |
| 248 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 249 | *object_hook*, if specified, will be called with the result of every JSON |
| 250 | object decoded and its return value will be used in place of the given |
| 251 | :class:`dict`. This can be used to provide custom deserializations (e.g. to |
| 252 | support JSON-RPC class hinting). |
| 253 | |
Raymond Hettinger | 9b8d069 | 2009-04-21 03:27:12 +0000 | [diff] [blame] | 254 | *object_pairs_hook*, if specified will be called with the result of every |
| 255 | JSON object decoded with an ordered list of pairs. The return value of |
| 256 | *object_pairs_hook* will be used instead of the :class:`dict`. This |
| 257 | feature can be used to implement custom decoders that rely on the order |
| 258 | that the key and value pairs are decoded (for example, |
| 259 | :func:`collections.OrderedDict` will remember the order of insertion). If |
| 260 | *object_hook* is also defined, the *object_pairs_hook* takes priority. |
| 261 | |
| 262 | .. versionchanged:: 3.1 |
Hirokazu Yamamoto | ae9eb5c | 2009-04-26 03:34:06 +0000 | [diff] [blame] | 263 | Added support for *object_pairs_hook*. |
Raymond Hettinger | 9b8d069 | 2009-04-21 03:27:12 +0000 | [diff] [blame] | 264 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 265 | *parse_float*, if specified, will be called with the string of every JSON |
| 266 | float to be decoded. By default, this is equivalent to ``float(num_str)``. |
| 267 | This can be used to use another datatype or parser for JSON floats |
| 268 | (e.g. :class:`decimal.Decimal`). |
| 269 | |
| 270 | *parse_int*, if specified, will be called with the string of every JSON int |
| 271 | to be decoded. By default, this is equivalent to ``int(num_str)``. This can |
| 272 | be used to use another datatype or parser for JSON integers |
| 273 | (e.g. :class:`float`). |
| 274 | |
| 275 | *parse_constant*, if specified, will be called with one of the following |
| 276 | strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``, ``'null'``, ``'true'``, |
| 277 | ``'false'``. This can be used to raise an exception if invalid JSON numbers |
| 278 | are encountered. |
| 279 | |
Georg Brandl | d4460aa | 2010-10-15 17:03:02 +0000 | [diff] [blame] | 280 | If *strict* is ``False`` (``True`` is the default), then control characters |
| 281 | will be allowed inside strings. Control characters in this context are |
| 282 | those with character codes in the 0-31 range, including ``'\t'`` (tab), |
| 283 | ``'\n'``, ``'\r'`` and ``'\0'``. |
| 284 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 285 | |
| 286 | .. method:: decode(s) |
| 287 | |
Benjamin Peterson | c6b607d | 2009-05-02 12:36:44 +0000 | [diff] [blame] | 288 | Return the Python representation of *s* (a :class:`str` instance |
| 289 | containing a JSON document) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 290 | |
| 291 | .. method:: raw_decode(s) |
| 292 | |
Benjamin Peterson | c6b607d | 2009-05-02 12:36:44 +0000 | [diff] [blame] | 293 | Decode a JSON document from *s* (a :class:`str` beginning with a |
| 294 | JSON document) and return a 2-tuple of the Python representation |
| 295 | and the index in *s* where the document ended. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 296 | |
| 297 | This can be used to decode a JSON document from a string that may have |
| 298 | extraneous data at the end. |
| 299 | |
| 300 | |
Georg Brandl | cd7f32b | 2009-06-08 09:13:45 +0000 | [diff] [blame] | 301 | .. class:: JSONEncoder(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 302 | |
| 303 | Extensible JSON encoder for Python data structures. |
| 304 | |
| 305 | Supports the following objects and types by default: |
| 306 | |
| 307 | +-------------------+---------------+ |
| 308 | | Python | JSON | |
| 309 | +===================+===============+ |
| 310 | | dict | object | |
| 311 | +-------------------+---------------+ |
| 312 | | list, tuple | array | |
| 313 | +-------------------+---------------+ |
Benjamin Peterson | c6b607d | 2009-05-02 12:36:44 +0000 | [diff] [blame] | 314 | | str | string | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 315 | +-------------------+---------------+ |
Georg Brandl | 639ce96 | 2009-04-11 18:18:16 +0000 | [diff] [blame] | 316 | | int, float | number | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 317 | +-------------------+---------------+ |
| 318 | | True | true | |
| 319 | +-------------------+---------------+ |
| 320 | | False | false | |
| 321 | +-------------------+---------------+ |
| 322 | | None | null | |
| 323 | +-------------------+---------------+ |
| 324 | |
| 325 | To extend this to recognize other objects, subclass and implement a |
| 326 | :meth:`default` method with another method that returns a serializable object |
| 327 | for ``o`` if possible, otherwise it should call the superclass implementation |
| 328 | (to raise :exc:`TypeError`). |
| 329 | |
| 330 | If *skipkeys* is ``False`` (the default), then it is a :exc:`TypeError` to |
Georg Brandl | 639ce96 | 2009-04-11 18:18:16 +0000 | [diff] [blame] | 331 | attempt encoding of keys that are not str, int, float or None. If |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 332 | *skipkeys* is ``True``, such items are simply skipped. |
| 333 | |
Benjamin Peterson | c6b607d | 2009-05-02 12:36:44 +0000 | [diff] [blame] | 334 | If *ensure_ascii* is ``True`` (the default), the output is guaranteed to |
| 335 | have all incoming non-ASCII characters escaped. If *ensure_ascii* is |
| 336 | ``False``, these characters will be output as-is. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 337 | |
| 338 | If *check_circular* is ``True`` (the default), then lists, dicts, and custom |
| 339 | encoded objects will be checked for circular references during encoding to |
| 340 | prevent an infinite recursion (which would cause an :exc:`OverflowError`). |
| 341 | Otherwise, no such check takes place. |
| 342 | |
| 343 | If *allow_nan* is ``True`` (the default), then ``NaN``, ``Infinity``, and |
| 344 | ``-Infinity`` will be encoded as such. This behavior is not JSON |
| 345 | specification compliant, but is consistent with most JavaScript based |
| 346 | encoders and decoders. Otherwise, it will be a :exc:`ValueError` to encode |
| 347 | such floats. |
| 348 | |
Georg Brandl | 6a74da3 | 2010-08-22 20:23:38 +0000 | [diff] [blame] | 349 | If *sort_keys* is ``True`` (default ``False``), then the output of dictionaries |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 350 | will be sorted by key; this is useful for regression tests to ensure that |
| 351 | JSON serializations can be compared on a day-to-day basis. |
| 352 | |
| 353 | If *indent* is a non-negative integer (it is ``None`` by default), then JSON |
| 354 | array elements and object members will be pretty-printed with that indent |
| 355 | level. An indent level of 0 will only insert newlines. ``None`` is the most |
| 356 | compact representation. |
| 357 | |
| 358 | If specified, *separators* should be an ``(item_separator, key_separator)`` |
| 359 | tuple. The default is ``(', ', ': ')``. To get the most compact JSON |
| 360 | representation, you should specify ``(',', ':')`` to eliminate whitespace. |
| 361 | |
| 362 | If specified, *default* is a function that gets called for objects that can't |
| 363 | otherwise be serialized. It should return a JSON encodable version of the |
| 364 | object or raise a :exc:`TypeError`. |
| 365 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 366 | |
| 367 | .. method:: default(o) |
| 368 | |
| 369 | Implement this method in a subclass such that it returns a serializable |
| 370 | object for *o*, or calls the base implementation (to raise a |
| 371 | :exc:`TypeError`). |
| 372 | |
| 373 | For example, to support arbitrary iterators, you could implement default |
| 374 | like this:: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 375 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 376 | def default(self, o): |
| 377 | try: |
Benjamin Peterson | e9bbc8b | 2008-09-28 02:06:32 +0000 | [diff] [blame] | 378 | iterable = iter(o) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 379 | except TypeError: |
Benjamin Peterson | e9bbc8b | 2008-09-28 02:06:32 +0000 | [diff] [blame] | 380 | pass |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 381 | else: |
| 382 | return list(iterable) |
Georg Brandl | 0bb73b8 | 2010-09-03 22:36:22 +0000 | [diff] [blame] | 383 | return json.JSONEncoder.default(self, o) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 384 | |
| 385 | |
| 386 | .. method:: encode(o) |
| 387 | |
| 388 | Return a JSON string representation of a Python data structure, *o*. For |
| 389 | example:: |
| 390 | |
Georg Brandl | 0bb73b8 | 2010-09-03 22:36:22 +0000 | [diff] [blame] | 391 | >>> json.JSONEncoder().encode({"foo": ["bar", "baz"]}) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 392 | '{"foo": ["bar", "baz"]}' |
| 393 | |
| 394 | |
| 395 | .. method:: iterencode(o) |
| 396 | |
| 397 | Encode the given object, *o*, and yield each string representation as |
| 398 | available. For example:: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 399 | |
Georg Brandl | 0bb73b8 | 2010-09-03 22:36:22 +0000 | [diff] [blame] | 400 | for chunk in json.JSONEncoder().iterencode(bigobject): |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 401 | mysocket.write(chunk) |