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