Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 1 | :mod:`json` --- JSON encoder and decoder |
| 2 | ======================================== |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 3 | |
| 4 | .. module:: json |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 5 | :synopsis: Encode and decode the JSON format. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 6 | .. moduleauthor:: Bob Ippolito <bob@redivi.com> |
| 7 | .. sectionauthor:: Bob Ippolito <bob@redivi.com> |
| 8 | .. versionadded:: 2.6 |
| 9 | |
Benjamin Peterson | 17e25d8 | 2011-02-27 15:09:14 +0000 | [diff] [blame] | 10 | `JSON (JavaScript Object Notation) <http://json.org>`_ is a subset of JavaScript |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 11 | syntax (ECMA-262 3rd edition) used as a lightweight data interchange format. |
| 12 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 13 | :mod:`json` exposes an API familiar to users of the standard library |
| 14 | :mod:`marshal` and :mod:`pickle` modules. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 15 | |
| 16 | Encoding basic Python object hierarchies:: |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 17 | |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 18 | >>> import json |
| 19 | >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) |
| 20 | '["foo", {"bar": ["baz", null, 1.0, 2]}]' |
| 21 | >>> print json.dumps("\"foo\bar") |
| 22 | "\"foo\bar" |
| 23 | >>> print json.dumps(u'\u1234') |
| 24 | "\u1234" |
| 25 | >>> print json.dumps('\\') |
| 26 | "\\" |
| 27 | >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) |
| 28 | {"a": 0, "b": 0, "c": 0} |
| 29 | >>> from StringIO import StringIO |
| 30 | >>> io = StringIO() |
| 31 | >>> json.dump(['streaming API'], io) |
| 32 | >>> io.getvalue() |
| 33 | '["streaming API"]' |
| 34 | |
| 35 | Compact encoding:: |
| 36 | |
| 37 | >>> import json |
| 38 | >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':')) |
| 39 | '[1,2,3,{"4":5,"6":7}]' |
| 40 | |
| 41 | Pretty printing:: |
| 42 | |
| 43 | >>> import json |
| 44 | >>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4) |
| 45 | { |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 46 | "4": 5, |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 47 | "6": 7 |
| 48 | } |
| 49 | |
| 50 | Decoding JSON:: |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 51 | |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 52 | >>> import json |
| 53 | >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') |
| 54 | [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] |
| 55 | >>> json.loads('"\\"foo\\bar"') |
| 56 | u'"foo\x08ar' |
| 57 | >>> from StringIO import StringIO |
| 58 | >>> io = StringIO('["streaming API"]') |
| 59 | >>> json.load(io) |
| 60 | [u'streaming API'] |
| 61 | |
| 62 | Specializing JSON object decoding:: |
| 63 | |
| 64 | >>> import json |
| 65 | >>> def as_complex(dct): |
| 66 | ... if '__complex__' in dct: |
| 67 | ... return complex(dct['real'], dct['imag']) |
| 68 | ... return dct |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 69 | ... |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 70 | >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', |
| 71 | ... object_hook=as_complex) |
| 72 | (1+2j) |
| 73 | >>> import decimal |
| 74 | >>> json.loads('1.1', parse_float=decimal.Decimal) |
| 75 | Decimal('1.1') |
| 76 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 77 | Extending :class:`JSONEncoder`:: |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 78 | |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 79 | >>> import json |
| 80 | >>> class ComplexEncoder(json.JSONEncoder): |
| 81 | ... def default(self, obj): |
| 82 | ... if isinstance(obj, complex): |
| 83 | ... return [obj.real, obj.imag] |
| 84 | ... return json.JSONEncoder.default(self, obj) |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 85 | ... |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 86 | >>> dumps(2 + 1j, cls=ComplexEncoder) |
| 87 | '[2.0, 1.0]' |
| 88 | >>> ComplexEncoder().encode(2 + 1j) |
| 89 | '[2.0, 1.0]' |
| 90 | >>> list(ComplexEncoder().iterencode(2 + 1j)) |
| 91 | ['[', '2.0', ', ', '1.0', ']'] |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 92 | |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 93 | |
| 94 | .. highlight:: none |
| 95 | |
| 96 | Using json.tool from the shell to validate and pretty-print:: |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 97 | |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 98 | $ echo '{"json":"obj"}' | python -mjson.tool |
| 99 | { |
| 100 | "json": "obj" |
| 101 | } |
| 102 | $ echo '{ 1.2:3.4}' | python -mjson.tool |
| 103 | Expecting property name: line 1 column 2 (char 2) |
| 104 | |
| 105 | .. highlight:: python |
| 106 | |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 107 | .. note:: |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 108 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 109 | The JSON produced by this module's default settings is a subset of |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 110 | YAML, so it may be used as a serializer for that as well. |
| 111 | |
| 112 | |
| 113 | Basic Usage |
| 114 | ----------- |
| 115 | |
| 116 | .. function:: dump(obj, fp[, skipkeys[, ensure_ascii[, check_circular[, allow_nan[, cls[, indent[, separators[, encoding[, default[, **kw]]]]]]]]]]) |
| 117 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 118 | Serialize *obj* as a JSON formatted stream to *fp* (a ``.write()``-supporting |
| 119 | file-like object). |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 120 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 121 | If *skipkeys* is ``True`` (default: ``False``), then dict keys that are not |
| 122 | of a basic type (:class:`str`, :class:`unicode`, :class:`int`, :class:`long`, |
| 123 | :class:`float`, :class:`bool`, ``None``) will be skipped instead of raising a |
| 124 | :exc:`TypeError`. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 125 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 126 | If *ensure_ascii* is ``False`` (default: ``True``), then some chunks written |
| 127 | to *fp* may be :class:`unicode` instances, subject to normal Python |
| 128 | :class:`str` to :class:`unicode` coercion rules. Unless ``fp.write()`` |
| 129 | explicitly understands :class:`unicode` (as in :func:`codecs.getwriter`) this |
| 130 | is likely to cause an error. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 131 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 132 | If *check_circular* is ``False`` (default: ``True``), then the circular |
| 133 | reference check for container types will be skipped and a circular reference |
| 134 | will result in an :exc:`OverflowError` (or worse). |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 135 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 136 | If *allow_nan* is ``False`` (default: ``True``), then it will be a |
| 137 | :exc:`ValueError` to serialize out of range :class:`float` values (``nan``, |
| 138 | ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of |
| 139 | using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 140 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 141 | If *indent* is a non-negative integer, then JSON array elements and object |
R David Murray | ea8b6ef | 2011-04-12 21:00:26 -0400 | [diff] [blame] | 142 | members will be pretty-printed with that indent level. An indent level of 0, |
| 143 | or negative, will only insert newlines. ``None`` (the default) selects the |
| 144 | most compact representation. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 145 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 146 | If *separators* is an ``(item_separator, dict_separator)`` tuple, then it |
| 147 | will be used instead of the default ``(', ', ': ')`` separators. ``(',', |
| 148 | ':')`` is the most compact JSON representation. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 149 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 150 | *encoding* is the character encoding for str instances, default is UTF-8. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 151 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 152 | *default(obj)* is a function that should return a serializable version of |
| 153 | *obj* or raise :exc:`TypeError`. The default simply raises :exc:`TypeError`. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 154 | |
Georg Brandl | fc29f27 | 2009-01-02 20:25:14 +0000 | [diff] [blame] | 155 | To use a custom :class:`JSONEncoder` subclass (e.g. one that overrides the |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 156 | :meth:`default` method to serialize additional types), specify it with the |
Georg Brandl | db949b8 | 2010-10-15 17:04:45 +0000 | [diff] [blame] | 157 | *cls* kwarg; otherwise :class:`JSONEncoder` is used. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 158 | |
Ezio Melotti | 6033d26 | 2011-04-15 07:37:00 +0300 | [diff] [blame] | 159 | .. note:: |
| 160 | |
| 161 | Unlike :mod:`pickle` and :mod:`marshal`, JSON is not a framed protocol so |
| 162 | trying to serialize more objects with repeated calls to :func:`dump` and |
| 163 | the same *fp* will result in an invalid JSON file. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 164 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 165 | .. function:: dumps(obj[, skipkeys[, ensure_ascii[, check_circular[, allow_nan[, cls[, indent[, separators[, encoding[, default[, **kw]]]]]]]]]]) |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 166 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 167 | Serialize *obj* to a JSON formatted :class:`str`. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 168 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 169 | If *ensure_ascii* is ``False``, then the return value will be a |
| 170 | :class:`unicode` instance. The other arguments have the same meaning as in |
| 171 | :func:`dump`. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 172 | |
Senthil Kumaran | e3d7354 | 2012-03-17 00:37:38 -0700 | [diff] [blame] | 173 | .. note:: |
| 174 | |
| 175 | Keys in key/value pairs of JSON are always of the type :class:`str`. When |
| 176 | a dictionary is converted into JSON, all the keys of the dictionary are |
| 177 | coerced to strings. As a result of this, if a dictionary is convered |
| 178 | into JSON and then back into a dictionary, the dictionary may not equal |
| 179 | the original one. That is, ``loads(dumps(x)) != x`` if x has non-string |
| 180 | keys. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 181 | |
Raymond Hettinger | 91852ca | 2009-03-19 19:19:03 +0000 | [diff] [blame] | 182 | .. function:: load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]]) |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 183 | |
| 184 | Deserialize *fp* (a ``.read()``-supporting file-like object containing a JSON |
| 185 | document) to a Python object. |
| 186 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 187 | If the contents of *fp* are encoded with an ASCII based encoding other than |
| 188 | UTF-8 (e.g. latin-1), then an appropriate *encoding* name must be specified. |
| 189 | Encodings that are not ASCII based (such as UCS-2) are not allowed, and |
Georg Brandl | 49cc4ea | 2009-04-23 08:44:57 +0000 | [diff] [blame] | 190 | should be wrapped with ``codecs.getreader(encoding)(fp)``, or simply decoded |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 191 | to a :class:`unicode` object and passed to :func:`loads`. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 192 | |
| 193 | *object_hook* is an optional function that will be called with the result of |
Andrew M. Kuchling | 1967200 | 2009-03-30 22:29:15 +0000 | [diff] [blame] | 194 | any object literal decoded (a :class:`dict`). The return value of |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 195 | *object_hook* will be used instead of the :class:`dict`. This feature can be used |
| 196 | to implement custom decoders (e.g. JSON-RPC class hinting). |
| 197 | |
Raymond Hettinger | 91852ca | 2009-03-19 19:19:03 +0000 | [diff] [blame] | 198 | *object_pairs_hook* is an optional function that will be called with the |
Andrew M. Kuchling | 1967200 | 2009-03-30 22:29:15 +0000 | [diff] [blame] | 199 | result of any object literal decoded with an ordered list of pairs. The |
Raymond Hettinger | 91852ca | 2009-03-19 19:19:03 +0000 | [diff] [blame] | 200 | return value of *object_pairs_hook* will be used instead of the |
| 201 | :class:`dict`. This feature can be used to implement custom decoders that |
| 202 | rely on the order that the key and value pairs are decoded (for example, |
| 203 | :func:`collections.OrderedDict` will remember the order of insertion). If |
| 204 | *object_hook* is also defined, the *object_pairs_hook* takes priority. |
| 205 | |
| 206 | .. versionchanged:: 2.7 |
| 207 | Added support for *object_pairs_hook*. |
| 208 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 209 | *parse_float*, if specified, will be called with the string of every JSON |
| 210 | float to be decoded. By default, this is equivalent to ``float(num_str)``. |
| 211 | This can be used to use another datatype or parser for JSON floats |
| 212 | (e.g. :class:`decimal.Decimal`). |
| 213 | |
| 214 | *parse_int*, if specified, will be called with the string of every JSON int |
| 215 | to be decoded. By default, this is equivalent to ``int(num_str)``. This can |
| 216 | be used to use another datatype or parser for JSON integers |
| 217 | (e.g. :class:`float`). |
| 218 | |
| 219 | *parse_constant*, if specified, will be called with one of the following |
| 220 | strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``, ``'null'``, ``'true'``, |
| 221 | ``'false'``. This can be used to raise an exception if invalid JSON numbers |
| 222 | are encountered. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 223 | |
| 224 | To use a custom :class:`JSONDecoder` subclass, specify it with the ``cls`` |
Georg Brandl | db949b8 | 2010-10-15 17:04:45 +0000 | [diff] [blame] | 225 | kwarg; otherwise :class:`JSONDecoder` is used. Additional keyword arguments |
| 226 | will be passed to the constructor of the class. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 227 | |
| 228 | |
Raymond Hettinger | 91852ca | 2009-03-19 19:19:03 +0000 | [diff] [blame] | 229 | .. function:: loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]]) |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 230 | |
| 231 | Deserialize *s* (a :class:`str` or :class:`unicode` instance containing a JSON |
| 232 | document) to a Python object. |
| 233 | |
| 234 | If *s* is a :class:`str` instance and is encoded with an ASCII based encoding |
| 235 | other than UTF-8 (e.g. latin-1), then an appropriate *encoding* name must be |
| 236 | specified. Encodings that are not ASCII based (such as UCS-2) are not |
| 237 | allowed and should be decoded to :class:`unicode` first. |
| 238 | |
Georg Brandl | c630195 | 2010-05-10 21:02:51 +0000 | [diff] [blame] | 239 | The other arguments have the same meaning as in :func:`load`. |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 240 | |
| 241 | |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 242 | Encoders and decoders |
| 243 | --------------------- |
| 244 | |
Raymond Hettinger | 91852ca | 2009-03-19 19:19:03 +0000 | [diff] [blame] | 245 | .. class:: JSONDecoder([encoding[, object_hook[, parse_float[, parse_int[, parse_constant[, strict[, object_pairs_hook]]]]]]]) |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 246 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 247 | Simple JSON decoder. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 248 | |
| 249 | Performs the following translations in decoding by default: |
| 250 | |
| 251 | +---------------+-------------------+ |
| 252 | | JSON | Python | |
| 253 | +===============+===================+ |
| 254 | | object | dict | |
| 255 | +---------------+-------------------+ |
| 256 | | array | list | |
| 257 | +---------------+-------------------+ |
| 258 | | string | unicode | |
| 259 | +---------------+-------------------+ |
| 260 | | number (int) | int, long | |
| 261 | +---------------+-------------------+ |
| 262 | | number (real) | float | |
| 263 | +---------------+-------------------+ |
| 264 | | true | True | |
| 265 | +---------------+-------------------+ |
| 266 | | false | False | |
| 267 | +---------------+-------------------+ |
| 268 | | null | None | |
| 269 | +---------------+-------------------+ |
| 270 | |
| 271 | It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their |
| 272 | corresponding ``float`` values, which is outside the JSON spec. |
| 273 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 274 | *encoding* determines the encoding used to interpret any :class:`str` objects |
| 275 | decoded by this instance (UTF-8 by default). It has no effect when decoding |
| 276 | :class:`unicode` objects. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 277 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 278 | Note that currently only encodings that are a superset of ASCII work, strings |
| 279 | of other encodings should be passed in as :class:`unicode`. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 280 | |
| 281 | *object_hook*, if specified, will be called with the result of every JSON |
| 282 | object decoded and its return value will be used in place of the given |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 283 | :class:`dict`. This can be used to provide custom deserializations (e.g. to |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 284 | support JSON-RPC class hinting). |
| 285 | |
Raymond Hettinger | 91852ca | 2009-03-19 19:19:03 +0000 | [diff] [blame] | 286 | *object_pairs_hook*, if specified will be called with the result of every |
| 287 | JSON object decoded with an ordered list of pairs. The return value of |
| 288 | *object_pairs_hook* will be used instead of the :class:`dict`. This |
| 289 | feature can be used to implement custom decoders that rely on the order |
| 290 | that the key and value pairs are decoded (for example, |
| 291 | :func:`collections.OrderedDict` will remember the order of insertion). If |
| 292 | *object_hook* is also defined, the *object_pairs_hook* takes priority. |
| 293 | |
| 294 | .. versionchanged:: 2.7 |
| 295 | Added support for *object_pairs_hook*. |
| 296 | |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 297 | *parse_float*, if specified, will be called with the string of every JSON |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 298 | float to be decoded. By default, this is equivalent to ``float(num_str)``. |
| 299 | This can be used to use another datatype or parser for JSON floats |
| 300 | (e.g. :class:`decimal.Decimal`). |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 301 | |
| 302 | *parse_int*, if specified, will be called with the string of every JSON int |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 303 | to be decoded. By default, this is equivalent to ``int(num_str)``. This can |
| 304 | be used to use another datatype or parser for JSON integers |
| 305 | (e.g. :class:`float`). |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 306 | |
| 307 | *parse_constant*, if specified, will be called with one of the following |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 308 | strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``, ``'null'``, ``'true'``, |
| 309 | ``'false'``. This can be used to raise an exception if invalid JSON numbers |
| 310 | are encountered. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 311 | |
Georg Brandl | db949b8 | 2010-10-15 17:04:45 +0000 | [diff] [blame] | 312 | If *strict* is ``False`` (``True`` is the default), then control characters |
| 313 | will be allowed inside strings. Control characters in this context are |
| 314 | those with character codes in the 0-31 range, including ``'\t'`` (tab), |
| 315 | ``'\n'``, ``'\r'`` and ``'\0'``. |
| 316 | |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 317 | |
| 318 | .. method:: decode(s) |
| 319 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 320 | Return the Python representation of *s* (a :class:`str` or |
| 321 | :class:`unicode` instance containing a JSON document) |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 322 | |
| 323 | .. method:: raw_decode(s) |
| 324 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 325 | Decode a JSON document from *s* (a :class:`str` or :class:`unicode` |
| 326 | beginning with a JSON document) and return a 2-tuple of the Python |
| 327 | representation and the index in *s* where the document ended. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 328 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 329 | This can be used to decode a JSON document from a string that may have |
| 330 | extraneous data at the end. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 331 | |
| 332 | |
| 333 | .. class:: JSONEncoder([skipkeys[, ensure_ascii[, check_circular[, allow_nan[, sort_keys[, indent[, separators[, encoding[, default]]]]]]]]]) |
| 334 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 335 | Extensible JSON encoder for Python data structures. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 336 | |
| 337 | Supports the following objects and types by default: |
| 338 | |
| 339 | +-------------------+---------------+ |
| 340 | | Python | JSON | |
| 341 | +===================+===============+ |
| 342 | | dict | object | |
| 343 | +-------------------+---------------+ |
| 344 | | list, tuple | array | |
| 345 | +-------------------+---------------+ |
| 346 | | str, unicode | string | |
| 347 | +-------------------+---------------+ |
| 348 | | int, long, float | number | |
| 349 | +-------------------+---------------+ |
| 350 | | True | true | |
| 351 | +-------------------+---------------+ |
| 352 | | False | false | |
| 353 | +-------------------+---------------+ |
| 354 | | None | null | |
| 355 | +-------------------+---------------+ |
| 356 | |
| 357 | To extend this to recognize other objects, subclass and implement a |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 358 | :meth:`default` method with another method that returns a serializable object |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 359 | for ``o`` if possible, otherwise it should call the superclass implementation |
| 360 | (to raise :exc:`TypeError`). |
| 361 | |
| 362 | If *skipkeys* is ``False`` (the default), then it is a :exc:`TypeError` to |
| 363 | attempt encoding of keys that are not str, int, long, float or None. If |
| 364 | *skipkeys* is ``True``, such items are simply skipped. |
| 365 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 366 | If *ensure_ascii* is ``True`` (the default), the output is guaranteed to be |
| 367 | :class:`str` objects with all incoming unicode characters escaped. If |
| 368 | *ensure_ascii* is ``False``, the output will be a unicode object. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 369 | |
| 370 | If *check_circular* is ``True`` (the default), then lists, dicts, and custom |
| 371 | encoded objects will be checked for circular references during encoding to |
| 372 | prevent an infinite recursion (which would cause an :exc:`OverflowError`). |
| 373 | Otherwise, no such check takes place. |
| 374 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 375 | If *allow_nan* is ``True`` (the default), then ``NaN``, ``Infinity``, and |
| 376 | ``-Infinity`` will be encoded as such. This behavior is not JSON |
| 377 | specification compliant, but is consistent with most JavaScript based |
| 378 | encoders and decoders. Otherwise, it will be a :exc:`ValueError` to encode |
| 379 | such floats. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 380 | |
Georg Brandl | 21946af | 2010-10-06 09:28:45 +0000 | [diff] [blame] | 381 | If *sort_keys* is ``True`` (default ``False``), then the output of dictionaries |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 382 | will be sorted by key; this is useful for regression tests to ensure that |
| 383 | JSON serializations can be compared on a day-to-day basis. |
| 384 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 385 | If *indent* is a non-negative integer (it is ``None`` by default), then JSON |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 386 | array elements and object members will be pretty-printed with that indent |
| 387 | level. An indent level of 0 will only insert newlines. ``None`` is the most |
| 388 | compact representation. |
| 389 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 390 | If specified, *separators* should be an ``(item_separator, key_separator)`` |
| 391 | tuple. The default is ``(', ', ': ')``. To get the most compact JSON |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 392 | representation, you should specify ``(',', ':')`` to eliminate whitespace. |
| 393 | |
| 394 | If specified, *default* is a function that gets called for objects that can't |
| 395 | otherwise be serialized. It should return a JSON encodable version of the |
| 396 | object or raise a :exc:`TypeError`. |
| 397 | |
| 398 | If *encoding* is not ``None``, then all input strings will be transformed |
| 399 | into unicode using that encoding prior to JSON-encoding. The default is |
| 400 | UTF-8. |
| 401 | |
| 402 | |
| 403 | .. method:: default(o) |
| 404 | |
| 405 | Implement this method in a subclass such that it returns a serializable |
| 406 | object for *o*, or calls the base implementation (to raise a |
| 407 | :exc:`TypeError`). |
| 408 | |
| 409 | For example, to support arbitrary iterators, you could implement default |
| 410 | like this:: |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 411 | |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 412 | def default(self, o): |
| 413 | try: |
Georg Brandl | 1379ae0 | 2008-09-24 09:47:55 +0000 | [diff] [blame] | 414 | iterable = iter(o) |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 415 | except TypeError: |
Georg Brandl | 1379ae0 | 2008-09-24 09:47:55 +0000 | [diff] [blame] | 416 | pass |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 417 | else: |
| 418 | return list(iterable) |
| 419 | return JSONEncoder.default(self, o) |
| 420 | |
| 421 | |
| 422 | .. method:: encode(o) |
| 423 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 424 | Return a JSON string representation of a Python data structure, *o*. For |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 425 | example:: |
| 426 | |
| 427 | >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) |
| 428 | '{"foo": ["bar", "baz"]}' |
| 429 | |
| 430 | |
| 431 | .. method:: iterencode(o) |
| 432 | |
| 433 | Encode the given object, *o*, and yield each string representation as |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 434 | available. For example:: |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 435 | |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 436 | for chunk in JSONEncoder().iterencode(bigobject): |
| 437 | mysocket.write(chunk) |