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 | ... |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 85 | >>> 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 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 | |
| 115 | .. function:: dump(obj, fp[, skipkeys[, ensure_ascii[, check_circular[, allow_nan[, cls[, indent[, separators[, encoding[, default[, **kw]]]]]]]]]]) |
| 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 |
Georg Brandl | 639ce96 | 2009-04-11 18:18:16 +0000 | [diff] [blame] | 121 | of a basic type (:class:`str`, :class:`unicode`, :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 | |
| 125 | If *ensure_ascii* is ``False`` (default: ``True``), then some chunks written |
| 126 | to *fp* may be :class:`unicode` instances, subject to normal Python |
| 127 | :class:`str` to :class:`unicode` coercion rules. Unless ``fp.write()`` |
| 128 | explicitly understands :class:`unicode` (as in :func:`codecs.getwriter`) this |
| 129 | is likely to cause an error. |
| 130 | |
| 131 | If *check_circular* is ``False`` (default: ``True``), then the circular |
| 132 | reference check for container types will be skipped and a circular reference |
| 133 | will result in an :exc:`OverflowError` (or worse). |
| 134 | |
| 135 | If *allow_nan* is ``False`` (default: ``True``), then it will be a |
| 136 | :exc:`ValueError` to serialize out of range :class:`float` values (``nan``, |
| 137 | ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of |
| 138 | using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). |
| 139 | |
| 140 | If *indent* is a non-negative integer, then JSON array elements and object |
| 141 | members will be pretty-printed with that indent level. An indent level of 0 |
| 142 | will only insert newlines. ``None`` (the default) selects the most compact |
| 143 | representation. |
| 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 | |
| 149 | *encoding* is the character encoding for str instances, default is UTF-8. |
| 150 | |
| 151 | *default(obj)* is a function that should return a serializable version of |
| 152 | *obj* or raise :exc:`TypeError`. The default simply raises :exc:`TypeError`. |
| 153 | |
Georg Brandl | 1f01deb | 2009-01-03 22:47:39 +0000 | [diff] [blame] | 154 | 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] | 155 | :meth:`default` method to serialize additional types), specify it with the |
| 156 | *cls* kwarg. |
| 157 | |
| 158 | |
| 159 | .. function:: dumps(obj[, skipkeys[, ensure_ascii[, check_circular[, allow_nan[, cls[, indent[, separators[, encoding[, default[, **kw]]]]]]]]]]) |
| 160 | |
| 161 | Serialize *obj* to a JSON formatted :class:`str`. |
| 162 | |
| 163 | If *ensure_ascii* is ``False``, then the return value will be a |
| 164 | :class:`unicode` instance. The other arguments have the same meaning as in |
| 165 | :func:`dump`. |
| 166 | |
| 167 | |
Raymond Hettinger | 9b8d069 | 2009-04-21 03:27:12 +0000 | [diff] [blame] | 168 | .. function:: load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]]) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 169 | |
| 170 | Deserialize *fp* (a ``.read()``-supporting file-like object containing a JSON |
| 171 | document) to a Python object. |
| 172 | |
| 173 | If the contents of *fp* are encoded with an ASCII based encoding other than |
| 174 | UTF-8 (e.g. latin-1), then an appropriate *encoding* name must be specified. |
| 175 | Encodings that are not ASCII based (such as UCS-2) are not allowed, and |
Georg Brandl | ff2ad0e | 2009-04-27 16:51:45 +0000 | [diff] [blame] | 176 | should be wrapped with ``codecs.getreader(encoding)(fp)``, or simply decoded |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 177 | to a :class:`unicode` object and passed to :func:`loads`. |
| 178 | |
| 179 | *object_hook* is an optional function that will be called with the result of |
| 180 | any object literal decode (a :class:`dict`). The return value of |
| 181 | *object_hook* will be used instead of the :class:`dict`. This feature can be used |
| 182 | to implement custom decoders (e.g. JSON-RPC class hinting). |
| 183 | |
Raymond Hettinger | 9b8d069 | 2009-04-21 03:27:12 +0000 | [diff] [blame] | 184 | *object_pairs_hook* is an optional function that will be called with the |
| 185 | result of any object literal decode with an ordered list of pairs. The |
| 186 | return value of *object_pairs_hook* will be used instead of the |
| 187 | :class:`dict`. This feature can be used to implement custom decoders that |
| 188 | rely on the order that the key and value pairs are decoded (for example, |
| 189 | :func:`collections.OrderedDict` will remember the order of insertion). If |
| 190 | *object_hook* is also defined, the *object_pairs_hook* takes priority. |
| 191 | |
| 192 | .. versionchanged:: 3.1 |
Hirokazu Yamamoto | ae9eb5c | 2009-04-26 03:34:06 +0000 | [diff] [blame] | 193 | Added support for *object_pairs_hook*. |
Raymond Hettinger | 9b8d069 | 2009-04-21 03:27:12 +0000 | [diff] [blame] | 194 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 195 | *parse_float*, if specified, will be called with the string of every JSON |
| 196 | float to be decoded. By default, this is equivalent to ``float(num_str)``. |
| 197 | This can be used to use another datatype or parser for JSON floats |
| 198 | (e.g. :class:`decimal.Decimal`). |
| 199 | |
| 200 | *parse_int*, if specified, will be called with the string of every JSON int |
| 201 | to be decoded. By default, this is equivalent to ``int(num_str)``. This can |
| 202 | be used to use another datatype or parser for JSON integers |
| 203 | (e.g. :class:`float`). |
| 204 | |
| 205 | *parse_constant*, if specified, will be called with one of the following |
| 206 | strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``, ``'null'``, ``'true'``, |
| 207 | ``'false'``. This can be used to raise an exception if invalid JSON numbers |
| 208 | are encountered. |
| 209 | |
| 210 | To use a custom :class:`JSONDecoder` subclass, specify it with the ``cls`` |
| 211 | kwarg. Additional keyword arguments will be passed to the constructor of the |
| 212 | class. |
| 213 | |
| 214 | |
Raymond Hettinger | 9b8d069 | 2009-04-21 03:27:12 +0000 | [diff] [blame] | 215 | .. function:: loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]]) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 216 | |
| 217 | Deserialize *s* (a :class:`str` or :class:`unicode` instance containing a JSON |
| 218 | document) to a Python object. |
| 219 | |
| 220 | If *s* is a :class:`str` instance and is encoded with an ASCII based encoding |
| 221 | other than UTF-8 (e.g. latin-1), then an appropriate *encoding* name must be |
| 222 | specified. Encodings that are not ASCII based (such as UCS-2) are not |
| 223 | allowed and should be decoded to :class:`unicode` first. |
| 224 | |
| 225 | The other arguments have the same meaning as in :func:`dump`. |
| 226 | |
| 227 | |
| 228 | Encoders and decoders |
| 229 | --------------------- |
| 230 | |
Raymond Hettinger | 9b8d069 | 2009-04-21 03:27:12 +0000 | [diff] [blame] | 231 | .. class:: JSONDecoder([encoding[, object_hook[, parse_float[, parse_int[, parse_constant[, strict[, object_pairs_hook]]]]]]]) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 232 | |
| 233 | Simple JSON decoder. |
| 234 | |
| 235 | Performs the following translations in decoding by default: |
| 236 | |
| 237 | +---------------+-------------------+ |
| 238 | | JSON | Python | |
| 239 | +===============+===================+ |
| 240 | | object | dict | |
| 241 | +---------------+-------------------+ |
| 242 | | array | list | |
| 243 | +---------------+-------------------+ |
| 244 | | string | unicode | |
| 245 | +---------------+-------------------+ |
Georg Brandl | 639ce96 | 2009-04-11 18:18:16 +0000 | [diff] [blame] | 246 | | number (int) | int | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 247 | +---------------+-------------------+ |
| 248 | | number (real) | float | |
| 249 | +---------------+-------------------+ |
| 250 | | true | True | |
| 251 | +---------------+-------------------+ |
| 252 | | false | False | |
| 253 | +---------------+-------------------+ |
| 254 | | null | None | |
| 255 | +---------------+-------------------+ |
| 256 | |
| 257 | It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their |
| 258 | corresponding ``float`` values, which is outside the JSON spec. |
| 259 | |
| 260 | *encoding* determines the encoding used to interpret any :class:`str` objects |
| 261 | decoded by this instance (UTF-8 by default). It has no effect when decoding |
| 262 | :class:`unicode` objects. |
| 263 | |
| 264 | Note that currently only encodings that are a superset of ASCII work, strings |
| 265 | of other encodings should be passed in as :class:`unicode`. |
| 266 | |
| 267 | *object_hook*, if specified, will be called with the result of every JSON |
| 268 | object decoded and its return value will be used in place of the given |
| 269 | :class:`dict`. This can be used to provide custom deserializations (e.g. to |
| 270 | support JSON-RPC class hinting). |
| 271 | |
Raymond Hettinger | 9b8d069 | 2009-04-21 03:27:12 +0000 | [diff] [blame] | 272 | *object_pairs_hook*, if specified will be called with the result of every |
| 273 | JSON object decoded with an ordered list of pairs. The return value of |
| 274 | *object_pairs_hook* will be used instead of the :class:`dict`. This |
| 275 | feature can be used to implement custom decoders that rely on the order |
| 276 | that the key and value pairs are decoded (for example, |
| 277 | :func:`collections.OrderedDict` will remember the order of insertion). If |
| 278 | *object_hook* is also defined, the *object_pairs_hook* takes priority. |
| 279 | |
| 280 | .. versionchanged:: 3.1 |
Hirokazu Yamamoto | ae9eb5c | 2009-04-26 03:34:06 +0000 | [diff] [blame] | 281 | Added support for *object_pairs_hook*. |
Raymond Hettinger | 9b8d069 | 2009-04-21 03:27:12 +0000 | [diff] [blame] | 282 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 283 | *parse_float*, if specified, will be called with the string of every JSON |
| 284 | float to be decoded. By default, this is equivalent to ``float(num_str)``. |
| 285 | This can be used to use another datatype or parser for JSON floats |
| 286 | (e.g. :class:`decimal.Decimal`). |
| 287 | |
| 288 | *parse_int*, if specified, will be called with the string of every JSON int |
| 289 | to be decoded. By default, this is equivalent to ``int(num_str)``. This can |
| 290 | be used to use another datatype or parser for JSON integers |
| 291 | (e.g. :class:`float`). |
| 292 | |
| 293 | *parse_constant*, if specified, will be called with one of the following |
| 294 | strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``, ``'null'``, ``'true'``, |
| 295 | ``'false'``. This can be used to raise an exception if invalid JSON numbers |
| 296 | are encountered. |
| 297 | |
| 298 | |
| 299 | .. method:: decode(s) |
| 300 | |
| 301 | Return the Python representation of *s* (a :class:`str` or |
| 302 | :class:`unicode` instance containing a JSON document) |
| 303 | |
| 304 | .. method:: raw_decode(s) |
| 305 | |
| 306 | Decode a JSON document from *s* (a :class:`str` or :class:`unicode` |
| 307 | beginning with a JSON document) and return a 2-tuple of the Python |
| 308 | representation and the index in *s* where the document ended. |
| 309 | |
| 310 | This can be used to decode a JSON document from a string that may have |
| 311 | extraneous data at the end. |
| 312 | |
| 313 | |
| 314 | .. class:: JSONEncoder([skipkeys[, ensure_ascii[, check_circular[, allow_nan[, sort_keys[, indent[, separators[, encoding[, default]]]]]]]]]) |
| 315 | |
| 316 | Extensible JSON encoder for Python data structures. |
| 317 | |
| 318 | Supports the following objects and types by default: |
| 319 | |
| 320 | +-------------------+---------------+ |
| 321 | | Python | JSON | |
| 322 | +===================+===============+ |
| 323 | | dict | object | |
| 324 | +-------------------+---------------+ |
| 325 | | list, tuple | array | |
| 326 | +-------------------+---------------+ |
| 327 | | str, unicode | string | |
| 328 | +-------------------+---------------+ |
Georg Brandl | 639ce96 | 2009-04-11 18:18:16 +0000 | [diff] [blame] | 329 | | int, float | number | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 330 | +-------------------+---------------+ |
| 331 | | True | true | |
| 332 | +-------------------+---------------+ |
| 333 | | False | false | |
| 334 | +-------------------+---------------+ |
| 335 | | None | null | |
| 336 | +-------------------+---------------+ |
| 337 | |
| 338 | To extend this to recognize other objects, subclass and implement a |
| 339 | :meth:`default` method with another method that returns a serializable object |
| 340 | for ``o`` if possible, otherwise it should call the superclass implementation |
| 341 | (to raise :exc:`TypeError`). |
| 342 | |
| 343 | 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] | 344 | 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] | 345 | *skipkeys* is ``True``, such items are simply skipped. |
| 346 | |
| 347 | If *ensure_ascii* is ``True`` (the default), the output is guaranteed to be |
| 348 | :class:`str` objects with all incoming unicode characters escaped. If |
| 349 | *ensure_ascii* is ``False``, the output will be a unicode object. |
| 350 | |
| 351 | If *check_circular* is ``True`` (the default), then lists, dicts, and custom |
| 352 | encoded objects will be checked for circular references during encoding to |
| 353 | prevent an infinite recursion (which would cause an :exc:`OverflowError`). |
| 354 | Otherwise, no such check takes place. |
| 355 | |
| 356 | If *allow_nan* is ``True`` (the default), then ``NaN``, ``Infinity``, and |
| 357 | ``-Infinity`` will be encoded as such. This behavior is not JSON |
| 358 | specification compliant, but is consistent with most JavaScript based |
| 359 | encoders and decoders. Otherwise, it will be a :exc:`ValueError` to encode |
| 360 | such floats. |
| 361 | |
| 362 | If *sort_keys* is ``True`` (the default), then the output of dictionaries |
| 363 | will be sorted by key; this is useful for regression tests to ensure that |
| 364 | JSON serializations can be compared on a day-to-day basis. |
| 365 | |
| 366 | If *indent* is a non-negative integer (it is ``None`` by default), then JSON |
| 367 | array elements and object members will be pretty-printed with that indent |
| 368 | level. An indent level of 0 will only insert newlines. ``None`` is the most |
| 369 | compact representation. |
| 370 | |
| 371 | If specified, *separators* should be an ``(item_separator, key_separator)`` |
| 372 | tuple. The default is ``(', ', ': ')``. To get the most compact JSON |
| 373 | representation, you should specify ``(',', ':')`` to eliminate whitespace. |
| 374 | |
| 375 | If specified, *default* is a function that gets called for objects that can't |
| 376 | otherwise be serialized. It should return a JSON encodable version of the |
| 377 | object or raise a :exc:`TypeError`. |
| 378 | |
| 379 | If *encoding* is not ``None``, then all input strings will be transformed |
| 380 | into unicode using that encoding prior to JSON-encoding. The default is |
| 381 | UTF-8. |
| 382 | |
| 383 | |
| 384 | .. method:: default(o) |
| 385 | |
| 386 | Implement this method in a subclass such that it returns a serializable |
| 387 | object for *o*, or calls the base implementation (to raise a |
| 388 | :exc:`TypeError`). |
| 389 | |
| 390 | For example, to support arbitrary iterators, you could implement default |
| 391 | like this:: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 392 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 393 | def default(self, o): |
| 394 | try: |
Benjamin Peterson | e9bbc8b | 2008-09-28 02:06:32 +0000 | [diff] [blame] | 395 | iterable = iter(o) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 396 | except TypeError: |
Benjamin Peterson | e9bbc8b | 2008-09-28 02:06:32 +0000 | [diff] [blame] | 397 | pass |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 398 | else: |
| 399 | return list(iterable) |
| 400 | return JSONEncoder.default(self, o) |
| 401 | |
| 402 | |
| 403 | .. method:: encode(o) |
| 404 | |
| 405 | Return a JSON string representation of a Python data structure, *o*. For |
| 406 | example:: |
| 407 | |
| 408 | >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) |
| 409 | '{"foo": ["bar", "baz"]}' |
| 410 | |
| 411 | |
| 412 | .. method:: iterencode(o) |
| 413 | |
| 414 | Encode the given object, *o*, and yield each string representation as |
| 415 | available. For example:: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 416 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 417 | for chunk in JSONEncoder().iterencode(bigobject): |
| 418 | mysocket.write(chunk) |