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 | |
Antoine Pitrou | f3e0a69 | 2012-08-24 19:46:17 +0200 | [diff] [blame^] | 10 | `JSON (JavaScript Object Notation) <http://json.org>`_, specified by |
| 11 | :rfc:`4627`, is a lightweight data interchange format based on a subset of |
| 12 | `JavaScript <http://en.wikipedia.org/wiki/JavaScript>`_ syntax (`ECMA-262 3rd |
| 13 | edition <http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf>`_). |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 14 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 15 | :mod:`json` exposes an API familiar to users of the standard library |
| 16 | :mod:`marshal` and :mod:`pickle` modules. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 17 | |
| 18 | Encoding basic Python object hierarchies:: |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 19 | |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 20 | >>> import json |
| 21 | >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) |
| 22 | '["foo", {"bar": ["baz", null, 1.0, 2]}]' |
| 23 | >>> print json.dumps("\"foo\bar") |
| 24 | "\"foo\bar" |
| 25 | >>> print json.dumps(u'\u1234') |
| 26 | "\u1234" |
| 27 | >>> print json.dumps('\\') |
| 28 | "\\" |
| 29 | >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) |
| 30 | {"a": 0, "b": 0, "c": 0} |
| 31 | >>> from StringIO import StringIO |
| 32 | >>> io = StringIO() |
| 33 | >>> json.dump(['streaming API'], io) |
| 34 | >>> io.getvalue() |
| 35 | '["streaming API"]' |
| 36 | |
| 37 | Compact encoding:: |
| 38 | |
| 39 | >>> import json |
| 40 | >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':')) |
| 41 | '[1,2,3,{"4":5,"6":7}]' |
| 42 | |
| 43 | Pretty printing:: |
| 44 | |
| 45 | >>> import json |
| 46 | >>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4) |
| 47 | { |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 48 | "4": 5, |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 49 | "6": 7 |
| 50 | } |
| 51 | |
| 52 | Decoding JSON:: |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 53 | |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 54 | >>> import json |
| 55 | >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') |
| 56 | [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] |
| 57 | >>> json.loads('"\\"foo\\bar"') |
| 58 | u'"foo\x08ar' |
| 59 | >>> from StringIO import StringIO |
| 60 | >>> io = StringIO('["streaming API"]') |
| 61 | >>> json.load(io) |
| 62 | [u'streaming API'] |
| 63 | |
| 64 | Specializing JSON object decoding:: |
| 65 | |
| 66 | >>> import json |
| 67 | >>> def as_complex(dct): |
| 68 | ... if '__complex__' in dct: |
| 69 | ... return complex(dct['real'], dct['imag']) |
| 70 | ... return dct |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 71 | ... |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 72 | >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', |
| 73 | ... object_hook=as_complex) |
| 74 | (1+2j) |
| 75 | >>> import decimal |
| 76 | >>> json.loads('1.1', parse_float=decimal.Decimal) |
| 77 | Decimal('1.1') |
| 78 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 79 | Extending :class:`JSONEncoder`:: |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 80 | |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 81 | >>> import json |
| 82 | >>> class ComplexEncoder(json.JSONEncoder): |
| 83 | ... def default(self, obj): |
| 84 | ... if isinstance(obj, complex): |
| 85 | ... return [obj.real, obj.imag] |
| 86 | ... return json.JSONEncoder.default(self, obj) |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 87 | ... |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 88 | >>> dumps(2 + 1j, cls=ComplexEncoder) |
| 89 | '[2.0, 1.0]' |
| 90 | >>> ComplexEncoder().encode(2 + 1j) |
| 91 | '[2.0, 1.0]' |
| 92 | >>> list(ComplexEncoder().iterencode(2 + 1j)) |
| 93 | ['[', '2.0', ', ', '1.0', ']'] |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 94 | |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 95 | |
| 96 | .. highlight:: none |
| 97 | |
| 98 | Using json.tool from the shell to validate and pretty-print:: |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 99 | |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 100 | $ echo '{"json":"obj"}' | python -mjson.tool |
| 101 | { |
| 102 | "json": "obj" |
| 103 | } |
Antoine Pitrou | d9a5137 | 2012-06-29 01:58:26 +0200 | [diff] [blame] | 104 | $ echo '{1.2:3.4}' | python -mjson.tool |
| 105 | Expecting property name enclosed in double quotes: line 1 column 1 (char 1) |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 106 | |
| 107 | .. highlight:: python |
| 108 | |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 109 | .. note:: |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 110 | |
Antoine Pitrou | f3e0a69 | 2012-08-24 19:46:17 +0200 | [diff] [blame^] | 111 | JSON is a subset of `YAML <http://yaml.org/>`_ 1.2. The JSON produced by |
| 112 | this module's default settings (in particular, the default *separators* |
| 113 | value) is also a subset of YAML 1.0 and 1.1. This module can thus also be |
| 114 | used as a YAML serializer. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 115 | |
| 116 | |
| 117 | Basic Usage |
| 118 | ----------- |
| 119 | |
| 120 | .. function:: dump(obj, fp[, skipkeys[, ensure_ascii[, check_circular[, allow_nan[, cls[, indent[, separators[, encoding[, default[, **kw]]]]]]]]]]) |
| 121 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 122 | Serialize *obj* as a JSON formatted stream to *fp* (a ``.write()``-supporting |
| 123 | file-like object). |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 124 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 125 | If *skipkeys* is ``True`` (default: ``False``), then dict keys that are not |
| 126 | of a basic type (:class:`str`, :class:`unicode`, :class:`int`, :class:`long`, |
| 127 | :class:`float`, :class:`bool`, ``None``) will be skipped instead of raising a |
| 128 | :exc:`TypeError`. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 129 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 130 | If *ensure_ascii* is ``False`` (default: ``True``), then some chunks written |
| 131 | to *fp* may be :class:`unicode` instances, subject to normal Python |
| 132 | :class:`str` to :class:`unicode` coercion rules. Unless ``fp.write()`` |
| 133 | explicitly understands :class:`unicode` (as in :func:`codecs.getwriter`) this |
| 134 | is likely to cause an error. |
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 *check_circular* is ``False`` (default: ``True``), then the circular |
| 137 | reference check for container types will be skipped and a circular reference |
| 138 | will result in an :exc:`OverflowError` (or worse). |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 139 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 140 | If *allow_nan* is ``False`` (default: ``True``), then it will be a |
| 141 | :exc:`ValueError` to serialize out of range :class:`float` values (``nan``, |
| 142 | ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of |
| 143 | using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 144 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 145 | 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] | 146 | members will be pretty-printed with that indent level. An indent level of 0, |
| 147 | or negative, will only insert newlines. ``None`` (the default) selects the |
| 148 | most compact 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 | If *separators* is an ``(item_separator, dict_separator)`` tuple, then it |
| 151 | will be used instead of the default ``(', ', ': ')`` separators. ``(',', |
| 152 | ':')`` is the most compact JSON representation. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 153 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 154 | *encoding* is the character encoding for str instances, default is UTF-8. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 155 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 156 | *default(obj)* is a function that should return a serializable version of |
| 157 | *obj* or raise :exc:`TypeError`. The default simply raises :exc:`TypeError`. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 158 | |
Georg Brandl | fc29f27 | 2009-01-02 20:25:14 +0000 | [diff] [blame] | 159 | 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] | 160 | :meth:`default` method to serialize additional types), specify it with the |
Georg Brandl | db949b8 | 2010-10-15 17:04:45 +0000 | [diff] [blame] | 161 | *cls* kwarg; otherwise :class:`JSONEncoder` is used. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 162 | |
Ezio Melotti | 6033d26 | 2011-04-15 07:37:00 +0300 | [diff] [blame] | 163 | .. note:: |
| 164 | |
| 165 | Unlike :mod:`pickle` and :mod:`marshal`, JSON is not a framed protocol so |
| 166 | trying to serialize more objects with repeated calls to :func:`dump` and |
| 167 | the same *fp* will result in an invalid JSON file. |
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 | .. 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] | 170 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 171 | Serialize *obj* to a JSON formatted :class:`str`. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 172 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 173 | If *ensure_ascii* is ``False``, then the return value will be a |
| 174 | :class:`unicode` instance. The other arguments have the same meaning as in |
| 175 | :func:`dump`. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 176 | |
Senthil Kumaran | e3d7354 | 2012-03-17 00:37:38 -0700 | [diff] [blame] | 177 | .. note:: |
| 178 | |
| 179 | Keys in key/value pairs of JSON are always of the type :class:`str`. When |
| 180 | a dictionary is converted into JSON, all the keys of the dictionary are |
| 181 | coerced to strings. As a result of this, if a dictionary is convered |
| 182 | into JSON and then back into a dictionary, the dictionary may not equal |
| 183 | the original one. That is, ``loads(dumps(x)) != x`` if x has non-string |
| 184 | keys. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 185 | |
Raymond Hettinger | 91852ca | 2009-03-19 19:19:03 +0000 | [diff] [blame] | 186 | .. 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] | 187 | |
| 188 | Deserialize *fp* (a ``.read()``-supporting file-like object containing a JSON |
| 189 | document) to a Python object. |
| 190 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 191 | If the contents of *fp* are encoded with an ASCII based encoding other than |
| 192 | UTF-8 (e.g. latin-1), then an appropriate *encoding* name must be specified. |
| 193 | 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] | 194 | should be wrapped with ``codecs.getreader(encoding)(fp)``, or simply decoded |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 195 | to a :class:`unicode` object and passed to :func:`loads`. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 196 | |
| 197 | *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] | 198 | any object literal decoded (a :class:`dict`). The return value of |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 199 | *object_hook* will be used instead of the :class:`dict`. This feature can be used |
Antoine Pitrou | f3e0a69 | 2012-08-24 19:46:17 +0200 | [diff] [blame^] | 200 | to implement custom decoders (e.g. `JSON-RPC <http://www.jsonrpc.org>`_ |
| 201 | class hinting). |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 202 | |
Raymond Hettinger | 91852ca | 2009-03-19 19:19:03 +0000 | [diff] [blame] | 203 | *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] | 204 | 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] | 205 | return value of *object_pairs_hook* will be used instead of the |
| 206 | :class:`dict`. This feature can be used to implement custom decoders that |
| 207 | rely on the order that the key and value pairs are decoded (for example, |
| 208 | :func:`collections.OrderedDict` will remember the order of insertion). If |
| 209 | *object_hook* is also defined, the *object_pairs_hook* takes priority. |
| 210 | |
| 211 | .. versionchanged:: 2.7 |
| 212 | Added support for *object_pairs_hook*. |
| 213 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 214 | *parse_float*, if specified, will be called with the string of every JSON |
| 215 | float to be decoded. By default, this is equivalent to ``float(num_str)``. |
| 216 | This can be used to use another datatype or parser for JSON floats |
| 217 | (e.g. :class:`decimal.Decimal`). |
| 218 | |
| 219 | *parse_int*, if specified, will be called with the string of every JSON int |
| 220 | to be decoded. By default, this is equivalent to ``int(num_str)``. This can |
| 221 | be used to use another datatype or parser for JSON integers |
| 222 | (e.g. :class:`float`). |
| 223 | |
| 224 | *parse_constant*, if specified, will be called with one of the following |
Hynek Schlawack | 019935f | 2012-05-16 18:02:54 +0200 | [diff] [blame] | 225 | strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. |
| 226 | This can be used to raise an exception if invalid JSON numbers |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 227 | are encountered. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 228 | |
Hynek Schlawack | 897b278 | 2012-05-20 11:50:41 +0200 | [diff] [blame] | 229 | .. versionchanged:: 2.7 |
| 230 | *parse_constant* doesn't get called on 'null', 'true', 'false' anymore. |
| 231 | |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 232 | To use a custom :class:`JSONDecoder` subclass, specify it with the ``cls`` |
Georg Brandl | db949b8 | 2010-10-15 17:04:45 +0000 | [diff] [blame] | 233 | kwarg; otherwise :class:`JSONDecoder` is used. Additional keyword arguments |
| 234 | will be passed to the constructor of the class. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 235 | |
| 236 | |
Raymond Hettinger | 91852ca | 2009-03-19 19:19:03 +0000 | [diff] [blame] | 237 | .. 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] | 238 | |
| 239 | Deserialize *s* (a :class:`str` or :class:`unicode` instance containing a JSON |
| 240 | document) to a Python object. |
| 241 | |
| 242 | If *s* is a :class:`str` instance and is encoded with an ASCII based encoding |
| 243 | other than UTF-8 (e.g. latin-1), then an appropriate *encoding* name must be |
| 244 | specified. Encodings that are not ASCII based (such as UCS-2) are not |
| 245 | allowed and should be decoded to :class:`unicode` first. |
| 246 | |
Georg Brandl | c630195 | 2010-05-10 21:02:51 +0000 | [diff] [blame] | 247 | The other arguments have the same meaning as in :func:`load`. |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 248 | |
| 249 | |
Antoine Pitrou | f3e0a69 | 2012-08-24 19:46:17 +0200 | [diff] [blame^] | 250 | Encoders and Decoders |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 251 | --------------------- |
| 252 | |
Raymond Hettinger | 91852ca | 2009-03-19 19:19:03 +0000 | [diff] [blame] | 253 | .. 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] | 254 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 255 | Simple JSON decoder. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 256 | |
| 257 | Performs the following translations in decoding by default: |
| 258 | |
| 259 | +---------------+-------------------+ |
| 260 | | JSON | Python | |
| 261 | +===============+===================+ |
| 262 | | object | dict | |
| 263 | +---------------+-------------------+ |
| 264 | | array | list | |
| 265 | +---------------+-------------------+ |
| 266 | | string | unicode | |
| 267 | +---------------+-------------------+ |
| 268 | | number (int) | int, long | |
| 269 | +---------------+-------------------+ |
| 270 | | number (real) | float | |
| 271 | +---------------+-------------------+ |
| 272 | | true | True | |
| 273 | +---------------+-------------------+ |
| 274 | | false | False | |
| 275 | +---------------+-------------------+ |
| 276 | | null | None | |
| 277 | +---------------+-------------------+ |
| 278 | |
| 279 | It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their |
| 280 | corresponding ``float`` values, which is outside the JSON spec. |
| 281 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 282 | *encoding* determines the encoding used to interpret any :class:`str` objects |
| 283 | decoded by this instance (UTF-8 by default). It has no effect when decoding |
| 284 | :class:`unicode` objects. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 285 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 286 | Note that currently only encodings that are a superset of ASCII work, strings |
| 287 | of other encodings should be passed in as :class:`unicode`. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 288 | |
| 289 | *object_hook*, if specified, will be called with the result of every JSON |
| 290 | 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] | 291 | :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] | 292 | support JSON-RPC class hinting). |
| 293 | |
Raymond Hettinger | 91852ca | 2009-03-19 19:19:03 +0000 | [diff] [blame] | 294 | *object_pairs_hook*, if specified will be called with the result of every |
| 295 | JSON object decoded with an ordered list of pairs. The return value of |
| 296 | *object_pairs_hook* will be used instead of the :class:`dict`. This |
| 297 | feature can be used to implement custom decoders that rely on the order |
| 298 | that the key and value pairs are decoded (for example, |
| 299 | :func:`collections.OrderedDict` will remember the order of insertion). If |
| 300 | *object_hook* is also defined, the *object_pairs_hook* takes priority. |
| 301 | |
| 302 | .. versionchanged:: 2.7 |
| 303 | Added support for *object_pairs_hook*. |
| 304 | |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 305 | *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] | 306 | float to be decoded. By default, this is equivalent to ``float(num_str)``. |
| 307 | This can be used to use another datatype or parser for JSON floats |
| 308 | (e.g. :class:`decimal.Decimal`). |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 309 | |
| 310 | *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] | 311 | to be decoded. By default, this is equivalent to ``int(num_str)``. This can |
| 312 | be used to use another datatype or parser for JSON integers |
| 313 | (e.g. :class:`float`). |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 314 | |
| 315 | *parse_constant*, if specified, will be called with one of the following |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 316 | strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``, ``'null'``, ``'true'``, |
| 317 | ``'false'``. This can be used to raise an exception if invalid JSON numbers |
| 318 | are encountered. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 319 | |
Georg Brandl | db949b8 | 2010-10-15 17:04:45 +0000 | [diff] [blame] | 320 | If *strict* is ``False`` (``True`` is the default), then control characters |
| 321 | will be allowed inside strings. Control characters in this context are |
| 322 | those with character codes in the 0-31 range, including ``'\t'`` (tab), |
| 323 | ``'\n'``, ``'\r'`` and ``'\0'``. |
| 324 | |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 325 | |
| 326 | .. method:: decode(s) |
| 327 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 328 | Return the Python representation of *s* (a :class:`str` or |
| 329 | :class:`unicode` instance containing a JSON document) |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 330 | |
| 331 | .. method:: raw_decode(s) |
| 332 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 333 | Decode a JSON document from *s* (a :class:`str` or :class:`unicode` |
| 334 | beginning with a JSON document) and return a 2-tuple of the Python |
| 335 | representation and the index in *s* where the document ended. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 336 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 337 | This can be used to decode a JSON document from a string that may have |
| 338 | extraneous data at the end. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 339 | |
| 340 | |
| 341 | .. class:: JSONEncoder([skipkeys[, ensure_ascii[, check_circular[, allow_nan[, sort_keys[, indent[, separators[, encoding[, default]]]]]]]]]) |
| 342 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 343 | Extensible JSON encoder for Python data structures. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 344 | |
| 345 | Supports the following objects and types by default: |
| 346 | |
| 347 | +-------------------+---------------+ |
| 348 | | Python | JSON | |
| 349 | +===================+===============+ |
| 350 | | dict | object | |
| 351 | +-------------------+---------------+ |
| 352 | | list, tuple | array | |
| 353 | +-------------------+---------------+ |
| 354 | | str, unicode | string | |
| 355 | +-------------------+---------------+ |
| 356 | | int, long, float | number | |
| 357 | +-------------------+---------------+ |
| 358 | | True | true | |
| 359 | +-------------------+---------------+ |
| 360 | | False | false | |
| 361 | +-------------------+---------------+ |
| 362 | | None | null | |
| 363 | +-------------------+---------------+ |
| 364 | |
| 365 | To extend this to recognize other objects, subclass and implement a |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 366 | :meth:`default` method with another method that returns a serializable object |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 367 | for ``o`` if possible, otherwise it should call the superclass implementation |
| 368 | (to raise :exc:`TypeError`). |
| 369 | |
| 370 | If *skipkeys* is ``False`` (the default), then it is a :exc:`TypeError` to |
| 371 | attempt encoding of keys that are not str, int, long, float or None. If |
| 372 | *skipkeys* is ``True``, such items are simply skipped. |
| 373 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 374 | If *ensure_ascii* is ``True`` (the default), the output is guaranteed to be |
| 375 | :class:`str` objects with all incoming unicode characters escaped. If |
| 376 | *ensure_ascii* is ``False``, the output will be a unicode object. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 377 | |
| 378 | If *check_circular* is ``True`` (the default), then lists, dicts, and custom |
| 379 | encoded objects will be checked for circular references during encoding to |
| 380 | prevent an infinite recursion (which would cause an :exc:`OverflowError`). |
| 381 | Otherwise, no such check takes place. |
| 382 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 383 | If *allow_nan* is ``True`` (the default), then ``NaN``, ``Infinity``, and |
| 384 | ``-Infinity`` will be encoded as such. This behavior is not JSON |
| 385 | specification compliant, but is consistent with most JavaScript based |
| 386 | encoders and decoders. Otherwise, it will be a :exc:`ValueError` to encode |
| 387 | such floats. |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 388 | |
Georg Brandl | 21946af | 2010-10-06 09:28:45 +0000 | [diff] [blame] | 389 | If *sort_keys* is ``True`` (default ``False``), then the output of dictionaries |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 390 | will be sorted by key; this is useful for regression tests to ensure that |
| 391 | JSON serializations can be compared on a day-to-day basis. |
| 392 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 393 | 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] | 394 | array elements and object members will be pretty-printed with that indent |
| 395 | level. An indent level of 0 will only insert newlines. ``None`` is the most |
| 396 | compact representation. |
| 397 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 398 | If specified, *separators* should be an ``(item_separator, key_separator)`` |
| 399 | tuple. The default is ``(', ', ': ')``. To get the most compact JSON |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 400 | representation, you should specify ``(',', ':')`` to eliminate whitespace. |
| 401 | |
| 402 | If specified, *default* is a function that gets called for objects that can't |
| 403 | otherwise be serialized. It should return a JSON encodable version of the |
| 404 | object or raise a :exc:`TypeError`. |
| 405 | |
| 406 | If *encoding* is not ``None``, then all input strings will be transformed |
| 407 | into unicode using that encoding prior to JSON-encoding. The default is |
| 408 | UTF-8. |
| 409 | |
| 410 | |
| 411 | .. method:: default(o) |
| 412 | |
| 413 | Implement this method in a subclass such that it returns a serializable |
| 414 | object for *o*, or calls the base implementation (to raise a |
| 415 | :exc:`TypeError`). |
| 416 | |
| 417 | For example, to support arbitrary iterators, you could implement default |
| 418 | like this:: |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 419 | |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 420 | def default(self, o): |
| 421 | try: |
Georg Brandl | 1379ae0 | 2008-09-24 09:47:55 +0000 | [diff] [blame] | 422 | iterable = iter(o) |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 423 | except TypeError: |
Georg Brandl | 1379ae0 | 2008-09-24 09:47:55 +0000 | [diff] [blame] | 424 | pass |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 425 | else: |
| 426 | return list(iterable) |
| 427 | return JSONEncoder.default(self, o) |
| 428 | |
| 429 | |
| 430 | .. method:: encode(o) |
| 431 | |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 432 | Return a JSON string representation of a Python data structure, *o*. For |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 433 | example:: |
| 434 | |
| 435 | >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) |
| 436 | '{"foo": ["bar", "baz"]}' |
| 437 | |
| 438 | |
| 439 | .. method:: iterencode(o) |
| 440 | |
| 441 | Encode the given object, *o*, and yield each string representation as |
Georg Brandl | 3961f18 | 2008-05-05 20:53:39 +0000 | [diff] [blame] | 442 | available. For example:: |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 443 | |
Brett Cannon | 4b964f9 | 2008-05-05 20:21:38 +0000 | [diff] [blame] | 444 | for chunk in JSONEncoder().iterencode(bigobject): |
| 445 | mysocket.write(chunk) |
Antoine Pitrou | f3e0a69 | 2012-08-24 19:46:17 +0200 | [diff] [blame^] | 446 | |
| 447 | |
| 448 | Standard Compliance |
| 449 | ------------------- |
| 450 | |
| 451 | The JSON format is specified by :rfc:`4627`. This section details this |
| 452 | module's level of compliance with the RFC. For simplicity, |
| 453 | :class:`JSONEncoder` and :class:`JSONDecoder` subclasses, and parameters other |
| 454 | than those explicitly mentioned, are not considered. |
| 455 | |
| 456 | This module does not comply with the RFC in a strict fashion, implementing some |
| 457 | extensions that are valid JavaScript but not valid JSON. In particular: |
| 458 | |
| 459 | - Top-level non-object, non-array values are accepted and output; |
| 460 | - Infinite and NaN number values are accepted and output; |
| 461 | - Repeated names within an object are accepted, and only the value of the last |
| 462 | name-value pair is used. |
| 463 | |
| 464 | Since the RFC permits RFC-compliant parsers to accept input texts that are not |
| 465 | RFC-compliant, this module's deserializer is technically RFC-compliant under |
| 466 | default settings. |
| 467 | |
| 468 | Character Encodings |
| 469 | ^^^^^^^^^^^^^^^^^^^ |
| 470 | |
| 471 | The RFC recommends that JSON be represented using either UTF-8, UTF-16, or |
| 472 | UTF-32, with UTF-8 being the default. Accordingly, this module uses UTF-8 as |
| 473 | the default for its *encoding* parameter. |
| 474 | |
| 475 | This module's deserializer only directly works with ASCII-compatible encodings; |
| 476 | UTF-16, UTF-32, and other ASCII-incompatible encodings require the use of |
| 477 | workarounds described in the documentation for the deserializer's *encoding* |
| 478 | parameter. |
| 479 | |
| 480 | The RFC also non-normatively describes a limited encoding detection technique |
| 481 | for JSON texts; this module's deserializer does not implement this or any other |
| 482 | kind of encoding detection. |
| 483 | |
| 484 | As permitted, though not required, by the RFC, this module's serializer sets |
| 485 | *ensure_ascii=True* by default, thus escaping the output so that the resulting |
| 486 | strings only contain ASCII characters. |
| 487 | |
| 488 | |
| 489 | Top-level Non-Object, Non-Array Values |
| 490 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 491 | |
| 492 | The RFC specifies that the top-level value of a JSON text must be either a |
| 493 | JSON object or array (Python :class:`dict` or :class:`list`). This module's |
| 494 | deserializer also accepts input texts consisting solely of a |
| 495 | JSON null, boolean, number, or string value:: |
| 496 | |
| 497 | >>> just_a_json_string = '"spam and eggs"' # Not by itself a valid JSON text |
| 498 | >>> json.loads(just_a_json_string) |
| 499 | u'spam and eggs' |
| 500 | |
| 501 | This module itself does not include a way to request that such input texts be |
| 502 | regarded as illegal. Likewise, this module's serializer also accepts single |
| 503 | Python :data:`None`, :class:`bool`, numeric, and :class:`str` |
| 504 | values as input and will generate output texts consisting solely of a top-level |
| 505 | JSON null, boolean, number, or string value without raising an exception:: |
| 506 | |
| 507 | >>> neither_a_list_nor_a_dict = u"spam and eggs" |
| 508 | >>> json.dumps(neither_a_list_nor_a_dict) # The result is not a valid JSON text |
| 509 | '"spam and eggs"' |
| 510 | |
| 511 | This module's serializer does not itself include a way to enforce the |
| 512 | aforementioned constraint. |
| 513 | |
| 514 | |
| 515 | Infinite and NaN Number Values |
| 516 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 517 | |
| 518 | The RFC does not permit the representation of infinite or NaN number values. |
| 519 | Despite that, by default, this module accepts and outputs ``Infinity``, |
| 520 | ``-Infinity``, and ``NaN`` as if they were valid JSON number literal values:: |
| 521 | |
| 522 | >>> # Neither of these calls raises an exception, but the results are not valid JSON |
| 523 | >>> json.dumps(float('-inf')) |
| 524 | '-Infinity' |
| 525 | >>> json.dumps(float('nan')) |
| 526 | 'NaN' |
| 527 | >>> # Same when deserializing |
| 528 | >>> json.loads('-Infinity') |
| 529 | -inf |
| 530 | >>> json.loads('NaN') |
| 531 | nan |
| 532 | |
| 533 | In the serializer, the *allow_nan* parameter can be used to alter this |
| 534 | behavior. In the deserializer, the *parse_constant* parameter can be used to |
| 535 | alter this behavior. |
| 536 | |
| 537 | |
| 538 | Repeated Names Within an Object |
| 539 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 540 | |
| 541 | The RFC specifies that the names within a JSON object should be unique, but |
| 542 | does not specify how repeated names in JSON objects should be handled. By |
| 543 | default, this module does not raise an exception; instead, it ignores all but |
| 544 | the last name-value pair for a given name:: |
| 545 | |
| 546 | >>> weird_json = '{"x": 1, "x": 2, "x": 3}' |
| 547 | >>> json.loads(weird_json) |
| 548 | {u'x': 3} |
| 549 | |
| 550 | The *object_pairs_hook* parameter can be used to alter this behavior. |