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