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. |
Terry Jan Reedy | fa089b9 | 2016-06-11 15:02:54 -0400 | [diff] [blame] | 6 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 7 | .. moduleauthor:: Bob Ippolito <bob@redivi.com> |
| 8 | .. sectionauthor:: Bob Ippolito <bob@redivi.com> |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 9 | |
Terry Jan Reedy | fa089b9 | 2016-06-11 15:02:54 -0400 | [diff] [blame] | 10 | **Source code:** :source:`Lib/json/__init__.py` |
| 11 | |
| 12 | -------------- |
| 13 | |
Antoine Pitrou | 331624b | 2012-08-24 19:37:23 +0200 | [diff] [blame] | 14 | `JSON (JavaScript Object Notation) <http://json.org>`_, specified by |
Serhiy Storchaka | 7a6915e | 2014-11-27 19:41:47 +0200 | [diff] [blame] | 15 | :rfc:`7159` (which obsoletes :rfc:`4627`) and by |
| 16 | `ECMA-404 <http://www.ecma-international.org/publications/standards/Ecma-404.htm>`_, |
| 17 | is a lightweight data interchange format inspired by |
Georg Brandl | 5d94134 | 2016-02-26 19:37:12 +0100 | [diff] [blame] | 18 | `JavaScript <https://en.wikipedia.org/wiki/JavaScript>`_ object literal syntax |
Serhiy Storchaka | 7a6915e | 2014-11-27 19:41:47 +0200 | [diff] [blame] | 19 | (although it is not a strict subset of JavaScript [#rfc-errata]_ ). |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 20 | |
| 21 | :mod:`json` exposes an API familiar to users of the standard library |
| 22 | :mod:`marshal` and :mod:`pickle` modules. |
| 23 | |
| 24 | Encoding basic Python object hierarchies:: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 25 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 26 | >>> import json |
| 27 | >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) |
| 28 | '["foo", {"bar": ["baz", null, 1.0, 2]}]' |
Neal Norwitz | 752abd0 | 2008-05-13 04:55:24 +0000 | [diff] [blame] | 29 | >>> print(json.dumps("\"foo\bar")) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 30 | "\"foo\bar" |
Benjamin Peterson | 2505bc6 | 2008-05-15 02:17:58 +0000 | [diff] [blame] | 31 | >>> print(json.dumps('\u1234')) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 32 | "\u1234" |
Neal Norwitz | 752abd0 | 2008-05-13 04:55:24 +0000 | [diff] [blame] | 33 | >>> print(json.dumps('\\')) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 34 | "\\" |
Neal Norwitz | 752abd0 | 2008-05-13 04:55:24 +0000 | [diff] [blame] | 35 | >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 36 | {"a": 0, "b": 0, "c": 0} |
Benjamin Peterson | 2505bc6 | 2008-05-15 02:17:58 +0000 | [diff] [blame] | 37 | >>> from io import StringIO |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 38 | >>> io = StringIO() |
| 39 | >>> json.dump(['streaming API'], io) |
| 40 | >>> io.getvalue() |
| 41 | '["streaming API"]' |
| 42 | |
| 43 | Compact encoding:: |
| 44 | |
| 45 | >>> import json |
Éric Araujo | de579d4 | 2011-04-21 02:37:41 +0200 | [diff] [blame] | 46 | >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',', ':')) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 47 | '[1,2,3,{"4":5,"6":7}]' |
| 48 | |
| 49 | Pretty printing:: |
| 50 | |
| 51 | >>> import json |
Neal Norwitz | 752abd0 | 2008-05-13 04:55:24 +0000 | [diff] [blame] | 52 | >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 53 | { |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 54 | "4": 5, |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 55 | "6": 7 |
| 56 | } |
| 57 | |
| 58 | Decoding JSON:: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 59 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 60 | >>> import json |
| 61 | >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') |
Benjamin Peterson | 2505bc6 | 2008-05-15 02:17:58 +0000 | [diff] [blame] | 62 | ['foo', {'bar': ['baz', None, 1.0, 2]}] |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 63 | >>> json.loads('"\\"foo\\bar"') |
Benjamin Peterson | 2505bc6 | 2008-05-15 02:17:58 +0000 | [diff] [blame] | 64 | '"foo\x08ar' |
| 65 | >>> from io import StringIO |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 66 | >>> io = StringIO('["streaming API"]') |
| 67 | >>> json.load(io) |
Benjamin Peterson | 2505bc6 | 2008-05-15 02:17:58 +0000 | [diff] [blame] | 68 | ['streaming API'] |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 69 | |
| 70 | Specializing JSON object decoding:: |
| 71 | |
| 72 | >>> import json |
| 73 | >>> def as_complex(dct): |
| 74 | ... if '__complex__' in dct: |
| 75 | ... return complex(dct['real'], dct['imag']) |
| 76 | ... return dct |
Benjamin Peterson | 2505bc6 | 2008-05-15 02:17:58 +0000 | [diff] [blame] | 77 | ... |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 78 | >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', |
| 79 | ... object_hook=as_complex) |
| 80 | (1+2j) |
| 81 | >>> import decimal |
| 82 | >>> json.loads('1.1', parse_float=decimal.Decimal) |
| 83 | Decimal('1.1') |
| 84 | |
| 85 | Extending :class:`JSONEncoder`:: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 86 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 87 | >>> import json |
| 88 | >>> class ComplexEncoder(json.JSONEncoder): |
| 89 | ... def default(self, obj): |
| 90 | ... if isinstance(obj, complex): |
| 91 | ... return [obj.real, obj.imag] |
R David Murray | dd24617 | 2013-03-17 21:52:35 -0400 | [diff] [blame] | 92 | ... # Let the base class default method raise the TypeError |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 93 | ... return json.JSONEncoder.default(self, obj) |
Benjamin Peterson | 2505bc6 | 2008-05-15 02:17:58 +0000 | [diff] [blame] | 94 | ... |
Georg Brandl | 0bb73b8 | 2010-09-03 22:36:22 +0000 | [diff] [blame] | 95 | >>> json.dumps(2 + 1j, cls=ComplexEncoder) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 96 | '[2.0, 1.0]' |
| 97 | >>> ComplexEncoder().encode(2 + 1j) |
| 98 | '[2.0, 1.0]' |
| 99 | >>> list(ComplexEncoder().iterencode(2 + 1j)) |
Georg Brandl | 0bb73b8 | 2010-09-03 22:36:22 +0000 | [diff] [blame] | 100 | ['[2.0', ', 1.0', ']'] |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 101 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 102 | |
Ezio Melotti | 84e59aa | 2012-04-13 21:02:18 -0600 | [diff] [blame] | 103 | .. highlight:: bash |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 104 | |
Serhiy Storchaka | 15287f8 | 2016-06-30 13:59:12 +0300 | [diff] [blame] | 105 | Using :mod:`json.tool` from the shell to validate and pretty-print:: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 106 | |
Georg Brandl | 946faa3 | 2014-10-28 22:54:24 +0100 | [diff] [blame] | 107 | $ echo '{"json":"obj"}' | python -m json.tool |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 108 | { |
| 109 | "json": "obj" |
| 110 | } |
Georg Brandl | 946faa3 | 2014-10-28 22:54:24 +0100 | [diff] [blame] | 111 | $ echo '{1.2:3.4}' | python -m json.tool |
Serhiy Storchaka | c510a04 | 2013-02-21 20:19:16 +0200 | [diff] [blame] | 112 | 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] | 113 | |
Benjamin Peterson | 940e207 | 2014-03-21 23:17:29 -0500 | [diff] [blame] | 114 | See :ref:`json-commandline` for detailed documentation. |
| 115 | |
Ezio Melotti | 84e59aa | 2012-04-13 21:02:18 -0600 | [diff] [blame] | 116 | .. highlight:: python3 |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 117 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 118 | .. note:: |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 119 | |
Antoine Pitrou | 331624b | 2012-08-24 19:37:23 +0200 | [diff] [blame] | 120 | JSON is a subset of `YAML <http://yaml.org/>`_ 1.2. The JSON produced by |
| 121 | this module's default settings (in particular, the default *separators* |
| 122 | value) is also a subset of YAML 1.0 and 1.1. This module can thus also be |
| 123 | used as a YAML serializer. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 124 | |
| 125 | |
| 126 | Basic Usage |
| 127 | ----------- |
| 128 | |
Serhiy Storchaka | aacd53f | 2016-06-22 00:03:20 +0300 | [diff] [blame] | 129 | .. function:: dump(obj, fp, *, skipkeys=False, ensure_ascii=True, \ |
Andrew Svetlov | 2ec53be | 2012-10-28 14:10:30 +0200 | [diff] [blame] | 130 | check_circular=True, allow_nan=True, cls=None, \ |
| 131 | indent=None, separators=None, default=None, \ |
| 132 | sort_keys=False, **kw) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 133 | |
| 134 | Serialize *obj* as a JSON formatted stream to *fp* (a ``.write()``-supporting |
Ezio Melotti | 6d2bc6e | 2013-03-29 03:59:29 +0200 | [diff] [blame] | 135 | :term:`file-like object`) using this :ref:`conversion table |
| 136 | <py-to-json-table>`. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 137 | |
Serhiy Storchaka | 15287f8 | 2016-06-30 13:59:12 +0300 | [diff] [blame] | 138 | If *skipkeys* is true (default: ``False``), then dict keys that are not |
Antoine Pitrou | 00d650b | 2011-01-21 21:37:32 +0000 | [diff] [blame] | 139 | of a basic type (:class:`str`, :class:`int`, :class:`float`, :class:`bool`, |
| 140 | ``None``) will be skipped instead of raising a :exc:`TypeError`. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 141 | |
Benjamin Peterson | c6b607d | 2009-05-02 12:36:44 +0000 | [diff] [blame] | 142 | The :mod:`json` module always produces :class:`str` objects, not |
| 143 | :class:`bytes` objects. Therefore, ``fp.write()`` must support :class:`str` |
| 144 | input. |
| 145 | |
Serhiy Storchaka | 15287f8 | 2016-06-30 13:59:12 +0300 | [diff] [blame] | 146 | If *ensure_ascii* is true (the default), the output is guaranteed to |
Éric Araujo | 6f7aa00 | 2012-01-16 10:09:20 +0100 | [diff] [blame] | 147 | have all incoming non-ASCII characters escaped. If *ensure_ascii* is |
Serhiy Storchaka | 15287f8 | 2016-06-30 13:59:12 +0300 | [diff] [blame] | 148 | false, these characters will be output as-is. |
Éric Araujo | 6f7aa00 | 2012-01-16 10:09:20 +0100 | [diff] [blame] | 149 | |
Serhiy Storchaka | 15287f8 | 2016-06-30 13:59:12 +0300 | [diff] [blame] | 150 | If *check_circular* is false (default: ``True``), then the circular |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 151 | reference check for container types will be skipped and a circular reference |
| 152 | will result in an :exc:`OverflowError` (or worse). |
| 153 | |
Serhiy Storchaka | 15287f8 | 2016-06-30 13:59:12 +0300 | [diff] [blame] | 154 | If *allow_nan* is false (default: ``True``), then it will be a |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 155 | :exc:`ValueError` to serialize out of range :class:`float` values (``nan``, |
Serhiy Storchaka | 15287f8 | 2016-06-30 13:59:12 +0300 | [diff] [blame] | 156 | ``inf``, ``-inf``) in strict compliance of the JSON specification. |
| 157 | If *allow_nan* is true, their JavaScript equivalents (``NaN``, |
| 158 | ``Infinity``, ``-Infinity``) will be used. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 159 | |
Raymond Hettinger | b643ef8 | 2010-10-31 08:00:16 +0000 | [diff] [blame] | 160 | If *indent* is a non-negative integer or string, then JSON array elements and |
| 161 | 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] | 162 | of 0, negative, or ``""`` will only insert newlines. ``None`` (the default) |
| 163 | selects the most compact representation. Using a positive integer indent |
Petri Lehtinen | 72c6eef | 2012-08-27 20:27:30 +0300 | [diff] [blame] | 164 | 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] | 165 | that string is used to indent each level. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 166 | |
Petri Lehtinen | 72b1426 | 2012-08-28 07:08:44 +0300 | [diff] [blame] | 167 | .. versionchanged:: 3.2 |
| 168 | Allow strings for *indent* in addition to integers. |
| 169 | |
Ezio Melotti | 1003144 | 2012-11-29 00:42:56 +0200 | [diff] [blame] | 170 | If specified, *separators* should be an ``(item_separator, key_separator)`` |
| 171 | tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and |
| 172 | ``(',', ': ')`` otherwise. To get the most compact JSON representation, |
| 173 | you should specify ``(',', ':')`` to eliminate whitespace. |
| 174 | |
| 175 | .. versionchanged:: 3.4 |
| 176 | Use ``(',', ': ')`` as default if *indent* is not ``None``. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 177 | |
Serhiy Storchaka | 15287f8 | 2016-06-30 13:59:12 +0300 | [diff] [blame] | 178 | If specified, *default* should be a function that gets called for objects that |
| 179 | can't otherwise be serialized. It should return a JSON encodable version of |
| 180 | the object or raise a :exc:`TypeError`. If not specified, :exc:`TypeError` |
| 181 | is raised. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 182 | |
Serhiy Storchaka | 15287f8 | 2016-06-30 13:59:12 +0300 | [diff] [blame] | 183 | If *sort_keys* is true (default: ``False``), then the output of |
Andrew Svetlov | 2ec53be | 2012-10-28 14:10:30 +0200 | [diff] [blame] | 184 | dictionaries will be sorted by key. |
| 185 | |
Georg Brandl | 1f01deb | 2009-01-03 22:47:39 +0000 | [diff] [blame] | 186 | 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] | 187 | :meth:`default` method to serialize additional types), specify it with the |
Georg Brandl | d4460aa | 2010-10-15 17:03:02 +0000 | [diff] [blame] | 188 | *cls* kwarg; otherwise :class:`JSONEncoder` is used. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 189 | |
Serhiy Storchaka | aacd53f | 2016-06-22 00:03:20 +0300 | [diff] [blame] | 190 | .. versionchanged:: 3.6 |
| 191 | All optional parameters are now :ref:`keyword-only <keyword-only_parameter>`. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 192 | |
Serhiy Storchaka | aacd53f | 2016-06-22 00:03:20 +0300 | [diff] [blame] | 193 | |
| 194 | .. function:: dumps(obj, *, skipkeys=False, ensure_ascii=True, \ |
Andrew Svetlov | 2ec53be | 2012-10-28 14:10:30 +0200 | [diff] [blame] | 195 | check_circular=True, allow_nan=True, cls=None, \ |
| 196 | indent=None, separators=None, default=None, \ |
| 197 | sort_keys=False, **kw) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 198 | |
Ezio Melotti | 6d2bc6e | 2013-03-29 03:59:29 +0200 | [diff] [blame] | 199 | Serialize *obj* to a JSON formatted :class:`str` using this :ref:`conversion |
| 200 | table <py-to-json-table>`. The arguments have the same meaning as in |
| 201 | :func:`dump`. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 202 | |
Ezio Melotti | 60adf95 | 2011-04-15 07:37:00 +0300 | [diff] [blame] | 203 | .. note:: |
| 204 | |
Georg Brandl | 340d269 | 2011-04-16 16:54:15 +0200 | [diff] [blame] | 205 | Unlike :mod:`pickle` and :mod:`marshal`, JSON is not a framed protocol, |
| 206 | so trying to serialize multiple objects with repeated calls to |
| 207 | :func:`dump` using the same *fp* will result in an invalid JSON file. |
| 208 | |
Senthil Kumaran | f2123d2 | 2012-03-17 00:40:34 -0700 | [diff] [blame] | 209 | .. note:: |
| 210 | |
| 211 | Keys in key/value pairs of JSON are always of the type :class:`str`. When |
| 212 | 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] | 213 | 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] | 214 | into JSON and then back into a dictionary, the dictionary may not equal |
| 215 | the original one. That is, ``loads(dumps(x)) != x`` if x has non-string |
| 216 | keys. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 217 | |
Serhiy Storchaka | aacd53f | 2016-06-22 00:03:20 +0300 | [diff] [blame] | 218 | .. 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] | 219 | |
Antoine Pitrou | 15251a9 | 2012-08-24 19:49:08 +0200 | [diff] [blame] | 220 | Deserialize *fp* (a ``.read()``-supporting :term:`file-like object` |
Ezio Melotti | 6d2bc6e | 2013-03-29 03:59:29 +0200 | [diff] [blame] | 221 | containing a JSON document) to a Python object using this :ref:`conversion |
| 222 | table <json-to-py-table>`. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 223 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 224 | *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] | 225 | any object literal decoded (a :class:`dict`). The return value of |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 226 | *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] | 227 | to implement custom decoders (e.g. `JSON-RPC <http://www.jsonrpc.org>`_ |
| 228 | class hinting). |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 229 | |
Raymond Hettinger | 9b8d069 | 2009-04-21 03:27:12 +0000 | [diff] [blame] | 230 | *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] | 231 | 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] | 232 | return value of *object_pairs_hook* will be used instead of the |
| 233 | :class:`dict`. This feature can be used to implement custom decoders that |
| 234 | rely on the order that the key and value pairs are decoded (for example, |
| 235 | :func:`collections.OrderedDict` will remember the order of insertion). If |
| 236 | *object_hook* is also defined, the *object_pairs_hook* takes priority. |
| 237 | |
| 238 | .. versionchanged:: 3.1 |
Hirokazu Yamamoto | ae9eb5c | 2009-04-26 03:34:06 +0000 | [diff] [blame] | 239 | Added support for *object_pairs_hook*. |
Raymond Hettinger | 9b8d069 | 2009-04-21 03:27:12 +0000 | [diff] [blame] | 240 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 241 | *parse_float*, if specified, will be called with the string of every JSON |
| 242 | float to be decoded. By default, this is equivalent to ``float(num_str)``. |
| 243 | This can be used to use another datatype or parser for JSON floats |
| 244 | (e.g. :class:`decimal.Decimal`). |
| 245 | |
| 246 | *parse_int*, if specified, will be called with the string of every JSON int |
| 247 | to be decoded. By default, this is equivalent to ``int(num_str)``. This can |
| 248 | be used to use another datatype or parser for JSON integers |
| 249 | (e.g. :class:`float`). |
| 250 | |
| 251 | *parse_constant*, if specified, will be called with one of the following |
Hynek Schlawack | 9729fd4 | 2012-05-16 19:01:04 +0200 | [diff] [blame] | 252 | strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. |
| 253 | This can be used to raise an exception if invalid JSON numbers |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 254 | are encountered. |
| 255 | |
Hynek Schlawack | f54c060 | 2012-05-20 18:32:53 +0200 | [diff] [blame] | 256 | .. versionchanged:: 3.1 |
Hynek Schlawack | 1203e83 | 2012-05-20 12:03:17 +0200 | [diff] [blame] | 257 | *parse_constant* doesn't get called on 'null', 'true', 'false' anymore. |
| 258 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 259 | To use a custom :class:`JSONDecoder` subclass, specify it with the ``cls`` |
Georg Brandl | d4460aa | 2010-10-15 17:03:02 +0000 | [diff] [blame] | 260 | kwarg; otherwise :class:`JSONDecoder` is used. Additional keyword arguments |
| 261 | will be passed to the constructor of the class. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 262 | |
Felix Crux | 60fb971 | 2013-08-12 17:39:51 -0400 | [diff] [blame] | 263 | If the data being deserialized is not a valid JSON document, a |
Serhiy Storchaka | 47efb4a | 2015-01-26 13:16:30 +0200 | [diff] [blame] | 264 | :exc:`JSONDecodeError` will be raised. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 265 | |
Serhiy Storchaka | aacd53f | 2016-06-22 00:03:20 +0300 | [diff] [blame] | 266 | .. versionchanged:: 3.6 |
| 267 | All optional parameters are now :ref:`keyword-only <keyword-only_parameter>`. |
| 268 | |
| 269 | .. 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] | 270 | |
Antoine Pitrou | 00d650b | 2011-01-21 21:37:32 +0000 | [diff] [blame] | 271 | Deserialize *s* (a :class:`str` instance containing a JSON document) to a |
Ezio Melotti | 6d2bc6e | 2013-03-29 03:59:29 +0200 | [diff] [blame] | 272 | Python object using this :ref:`conversion table <json-to-py-table>`. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 273 | |
Antoine Pitrou | 00d650b | 2011-01-21 21:37:32 +0000 | [diff] [blame] | 274 | The other arguments have the same meaning as in :func:`load`, except |
| 275 | *encoding* which is ignored and deprecated. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 276 | |
Felix Crux | b435799 | 2013-08-12 17:39:51 -0400 | [diff] [blame] | 277 | If the data being deserialized is not a valid JSON document, a |
Serhiy Storchaka | 47efb4a | 2015-01-26 13:16:30 +0200 | [diff] [blame] | 278 | :exc:`JSONDecodeError` will be raised. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 279 | |
Antoine Pitrou | 331624b | 2012-08-24 19:37:23 +0200 | [diff] [blame] | 280 | Encoders and Decoders |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 281 | --------------------- |
| 282 | |
Serhiy Storchaka | aacd53f | 2016-06-22 00:03:20 +0300 | [diff] [blame] | 283 | .. 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] | 284 | |
| 285 | Simple JSON decoder. |
| 286 | |
| 287 | Performs the following translations in decoding by default: |
| 288 | |
Ezio Melotti | 6d2bc6e | 2013-03-29 03:59:29 +0200 | [diff] [blame] | 289 | .. _json-to-py-table: |
| 290 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 291 | +---------------+-------------------+ |
| 292 | | JSON | Python | |
| 293 | +===============+===================+ |
| 294 | | object | dict | |
| 295 | +---------------+-------------------+ |
| 296 | | array | list | |
| 297 | +---------------+-------------------+ |
Benjamin Peterson | c6b607d | 2009-05-02 12:36:44 +0000 | [diff] [blame] | 298 | | string | str | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 299 | +---------------+-------------------+ |
Georg Brandl | 639ce96 | 2009-04-11 18:18:16 +0000 | [diff] [blame] | 300 | | number (int) | int | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 301 | +---------------+-------------------+ |
| 302 | | number (real) | float | |
| 303 | +---------------+-------------------+ |
| 304 | | true | True | |
| 305 | +---------------+-------------------+ |
| 306 | | false | False | |
| 307 | +---------------+-------------------+ |
| 308 | | null | None | |
| 309 | +---------------+-------------------+ |
| 310 | |
| 311 | It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their |
| 312 | corresponding ``float`` values, which is outside the JSON spec. |
| 313 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 314 | *object_hook*, if specified, will be called with the result of every JSON |
| 315 | object decoded and its return value will be used in place of the given |
| 316 | :class:`dict`. This can be used to provide custom deserializations (e.g. to |
| 317 | support JSON-RPC class hinting). |
| 318 | |
Raymond Hettinger | 9b8d069 | 2009-04-21 03:27:12 +0000 | [diff] [blame] | 319 | *object_pairs_hook*, if specified will be called with the result of every |
| 320 | JSON object decoded with an ordered list of pairs. The return value of |
| 321 | *object_pairs_hook* will be used instead of the :class:`dict`. This |
| 322 | feature can be used to implement custom decoders that rely on the order |
| 323 | that the key and value pairs are decoded (for example, |
| 324 | :func:`collections.OrderedDict` will remember the order of insertion). If |
| 325 | *object_hook* is also defined, the *object_pairs_hook* takes priority. |
| 326 | |
| 327 | .. versionchanged:: 3.1 |
Hirokazu Yamamoto | ae9eb5c | 2009-04-26 03:34:06 +0000 | [diff] [blame] | 328 | Added support for *object_pairs_hook*. |
Raymond Hettinger | 9b8d069 | 2009-04-21 03:27:12 +0000 | [diff] [blame] | 329 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 330 | *parse_float*, if specified, will be called with the string of every JSON |
| 331 | float to be decoded. By default, this is equivalent to ``float(num_str)``. |
| 332 | This can be used to use another datatype or parser for JSON floats |
| 333 | (e.g. :class:`decimal.Decimal`). |
| 334 | |
| 335 | *parse_int*, if specified, will be called with the string of every JSON int |
| 336 | to be decoded. By default, this is equivalent to ``int(num_str)``. This can |
| 337 | be used to use another datatype or parser for JSON integers |
| 338 | (e.g. :class:`float`). |
| 339 | |
| 340 | *parse_constant*, if specified, will be called with one of the following |
| 341 | strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``, ``'null'``, ``'true'``, |
| 342 | ``'false'``. This can be used to raise an exception if invalid JSON numbers |
| 343 | are encountered. |
| 344 | |
Serhiy Storchaka | 15287f8 | 2016-06-30 13:59:12 +0300 | [diff] [blame] | 345 | If *strict* is false (``True`` is the default), then control characters |
Georg Brandl | d4460aa | 2010-10-15 17:03:02 +0000 | [diff] [blame] | 346 | will be allowed inside strings. Control characters in this context are |
| 347 | those with character codes in the 0-31 range, including ``'\t'`` (tab), |
| 348 | ``'\n'``, ``'\r'`` and ``'\0'``. |
| 349 | |
Felix Crux | 654f003 | 2013-08-12 17:39:51 -0400 | [diff] [blame] | 350 | If the data being deserialized is not a valid JSON document, a |
Serhiy Storchaka | 47efb4a | 2015-01-26 13:16:30 +0200 | [diff] [blame] | 351 | :exc:`JSONDecodeError` will be raised. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 352 | |
Serhiy Storchaka | aacd53f | 2016-06-22 00:03:20 +0300 | [diff] [blame] | 353 | .. versionchanged:: 3.6 |
| 354 | All parameters are now :ref:`keyword-only <keyword-only_parameter>`. |
| 355 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 356 | .. method:: decode(s) |
| 357 | |
Benjamin Peterson | c6b607d | 2009-05-02 12:36:44 +0000 | [diff] [blame] | 358 | Return the Python representation of *s* (a :class:`str` instance |
Martin Panter | d21e0b5 | 2015-10-10 10:36:22 +0000 | [diff] [blame] | 359 | containing a JSON document). |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 360 | |
Serhiy Storchaka | 47efb4a | 2015-01-26 13:16:30 +0200 | [diff] [blame] | 361 | :exc:`JSONDecodeError` will be raised if the given JSON document is not |
| 362 | valid. |
| 363 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 364 | .. method:: raw_decode(s) |
| 365 | |
Benjamin Peterson | c6b607d | 2009-05-02 12:36:44 +0000 | [diff] [blame] | 366 | Decode a JSON document from *s* (a :class:`str` beginning with a |
| 367 | JSON document) and return a 2-tuple of the Python representation |
| 368 | and the index in *s* where the document ended. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 369 | |
| 370 | This can be used to decode a JSON document from a string that may have |
| 371 | extraneous data at the end. |
| 372 | |
| 373 | |
Serhiy Storchaka | aacd53f | 2016-06-22 00:03:20 +0300 | [diff] [blame] | 374 | .. 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] | 375 | |
| 376 | Extensible JSON encoder for Python data structures. |
| 377 | |
| 378 | Supports the following objects and types by default: |
| 379 | |
Ezio Melotti | 6d2bc6e | 2013-03-29 03:59:29 +0200 | [diff] [blame] | 380 | .. _py-to-json-table: |
| 381 | |
Ethan Furman | a4998a7 | 2013-08-10 13:01:45 -0700 | [diff] [blame] | 382 | +----------------------------------------+---------------+ |
| 383 | | Python | JSON | |
| 384 | +========================================+===============+ |
| 385 | | dict | object | |
| 386 | +----------------------------------------+---------------+ |
| 387 | | list, tuple | array | |
| 388 | +----------------------------------------+---------------+ |
| 389 | | str | string | |
| 390 | +----------------------------------------+---------------+ |
| 391 | | int, float, int- & float-derived Enums | number | |
| 392 | +----------------------------------------+---------------+ |
| 393 | | True | true | |
| 394 | +----------------------------------------+---------------+ |
| 395 | | False | false | |
| 396 | +----------------------------------------+---------------+ |
| 397 | | None | null | |
| 398 | +----------------------------------------+---------------+ |
| 399 | |
| 400 | .. versionchanged:: 3.4 |
| 401 | Added support for int- and float-derived Enum classes. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 402 | |
| 403 | To extend this to recognize other objects, subclass and implement a |
| 404 | :meth:`default` method with another method that returns a serializable object |
| 405 | for ``o`` if possible, otherwise it should call the superclass implementation |
| 406 | (to raise :exc:`TypeError`). |
| 407 | |
Serhiy Storchaka | 15287f8 | 2016-06-30 13:59:12 +0300 | [diff] [blame] | 408 | 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] | 409 | attempt encoding of keys that are not str, int, float or None. If |
Serhiy Storchaka | 15287f8 | 2016-06-30 13:59:12 +0300 | [diff] [blame] | 410 | *skipkeys* is true, such items are simply skipped. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 411 | |
Serhiy Storchaka | 15287f8 | 2016-06-30 13:59:12 +0300 | [diff] [blame] | 412 | If *ensure_ascii* is true (the default), the output is guaranteed to |
Benjamin Peterson | c6b607d | 2009-05-02 12:36:44 +0000 | [diff] [blame] | 413 | have all incoming non-ASCII characters escaped. If *ensure_ascii* is |
Serhiy Storchaka | 15287f8 | 2016-06-30 13:59:12 +0300 | [diff] [blame] | 414 | false, these characters will be output as-is. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 415 | |
Serhiy Storchaka | 15287f8 | 2016-06-30 13:59:12 +0300 | [diff] [blame] | 416 | If *check_circular* is true (the default), then lists, dicts, and custom |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 417 | encoded objects will be checked for circular references during encoding to |
| 418 | prevent an infinite recursion (which would cause an :exc:`OverflowError`). |
| 419 | Otherwise, no such check takes place. |
| 420 | |
Serhiy Storchaka | 15287f8 | 2016-06-30 13:59:12 +0300 | [diff] [blame] | 421 | If *allow_nan* is true (the default), then ``NaN``, ``Infinity``, and |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 422 | ``-Infinity`` will be encoded as such. This behavior is not JSON |
| 423 | specification compliant, but is consistent with most JavaScript based |
| 424 | encoders and decoders. Otherwise, it will be a :exc:`ValueError` to encode |
| 425 | such floats. |
| 426 | |
Serhiy Storchaka | 15287f8 | 2016-06-30 13:59:12 +0300 | [diff] [blame] | 427 | If *sort_keys* is true (default: ``False``), then the output of dictionaries |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 428 | will be sorted by key; this is useful for regression tests to ensure that |
| 429 | JSON serializations can be compared on a day-to-day basis. |
| 430 | |
Petri Lehtinen | 72b1426 | 2012-08-28 07:08:44 +0300 | [diff] [blame] | 431 | If *indent* is a non-negative integer or string, then JSON array elements and |
| 432 | object members will be pretty-printed with that indent level. An indent level |
| 433 | of 0, negative, or ``""`` will only insert newlines. ``None`` (the default) |
| 434 | selects the most compact representation. Using a positive integer indent |
| 435 | indents that many spaces per level. If *indent* is a string (such as ``"\t"``), |
| 436 | that string is used to indent each level. |
| 437 | |
| 438 | .. versionchanged:: 3.2 |
| 439 | Allow strings for *indent* in addition to integers. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 440 | |
| 441 | If specified, *separators* should be an ``(item_separator, key_separator)`` |
Ezio Melotti | 1003144 | 2012-11-29 00:42:56 +0200 | [diff] [blame] | 442 | tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and |
| 443 | ``(',', ': ')`` otherwise. To get the most compact JSON representation, |
| 444 | you should specify ``(',', ':')`` to eliminate whitespace. |
| 445 | |
| 446 | .. versionchanged:: 3.4 |
| 447 | Use ``(',', ': ')`` as default if *indent* is not ``None``. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 448 | |
Serhiy Storchaka | 15287f8 | 2016-06-30 13:59:12 +0300 | [diff] [blame] | 449 | If specified, *default* should be a function that gets called for objects that |
| 450 | can't otherwise be serialized. It should return a JSON encodable version of |
| 451 | the object or raise a :exc:`TypeError`. If not specified, :exc:`TypeError` |
| 452 | is raised. |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 453 | |
Serhiy Storchaka | aacd53f | 2016-06-22 00:03:20 +0300 | [diff] [blame] | 454 | .. versionchanged:: 3.6 |
| 455 | All parameters are now :ref:`keyword-only <keyword-only_parameter>`. |
| 456 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 457 | |
| 458 | .. method:: default(o) |
| 459 | |
| 460 | Implement this method in a subclass such that it returns a serializable |
| 461 | object for *o*, or calls the base implementation (to raise a |
| 462 | :exc:`TypeError`). |
| 463 | |
| 464 | For example, to support arbitrary iterators, you could implement default |
| 465 | like this:: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 466 | |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 467 | def default(self, o): |
| 468 | try: |
Benjamin Peterson | e9bbc8b | 2008-09-28 02:06:32 +0000 | [diff] [blame] | 469 | iterable = iter(o) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 470 | except TypeError: |
Benjamin Peterson | e9bbc8b | 2008-09-28 02:06:32 +0000 | [diff] [blame] | 471 | pass |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 472 | else: |
| 473 | return list(iterable) |
R David Murray | dd24617 | 2013-03-17 21:52:35 -0400 | [diff] [blame] | 474 | # Let the base class default method raise the TypeError |
Georg Brandl | 0bb73b8 | 2010-09-03 22:36:22 +0000 | [diff] [blame] | 475 | return json.JSONEncoder.default(self, o) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 476 | |
| 477 | |
| 478 | .. method:: encode(o) |
| 479 | |
| 480 | Return a JSON string representation of a Python data structure, *o*. For |
| 481 | example:: |
| 482 | |
Georg Brandl | 0bb73b8 | 2010-09-03 22:36:22 +0000 | [diff] [blame] | 483 | >>> json.JSONEncoder().encode({"foo": ["bar", "baz"]}) |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 484 | '{"foo": ["bar", "baz"]}' |
| 485 | |
| 486 | |
| 487 | .. method:: iterencode(o) |
| 488 | |
| 489 | Encode the given object, *o*, and yield each string representation as |
| 490 | available. For example:: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 491 | |
Georg Brandl | 0bb73b8 | 2010-09-03 22:36:22 +0000 | [diff] [blame] | 492 | for chunk in json.JSONEncoder().iterencode(bigobject): |
Christian Heimes | 9054000 | 2008-05-08 14:29:10 +0000 | [diff] [blame] | 493 | mysocket.write(chunk) |
Antoine Pitrou | 331624b | 2012-08-24 19:37:23 +0200 | [diff] [blame] | 494 | |
| 495 | |
Serhiy Storchaka | 47efb4a | 2015-01-26 13:16:30 +0200 | [diff] [blame] | 496 | Exceptions |
| 497 | ---------- |
| 498 | |
| 499 | .. exception:: JSONDecodeError(msg, doc, pos, end=None) |
| 500 | |
| 501 | Subclass of :exc:`ValueError` with the following additional attributes: |
| 502 | |
| 503 | .. attribute:: msg |
| 504 | |
| 505 | The unformatted error message. |
| 506 | |
| 507 | .. attribute:: doc |
| 508 | |
| 509 | The JSON document being parsed. |
| 510 | |
| 511 | .. attribute:: pos |
| 512 | |
| 513 | The start index of *doc* where parsing failed. |
| 514 | |
| 515 | .. attribute:: lineno |
| 516 | |
| 517 | The line corresponding to *pos*. |
| 518 | |
| 519 | .. attribute:: colno |
| 520 | |
| 521 | The column corresponding to *pos*. |
| 522 | |
| 523 | .. versionadded:: 3.5 |
| 524 | |
| 525 | |
Serhiy Storchaka | 7a6915e | 2014-11-27 19:41:47 +0200 | [diff] [blame] | 526 | Standard Compliance and Interoperability |
| 527 | ---------------------------------------- |
Antoine Pitrou | 331624b | 2012-08-24 19:37:23 +0200 | [diff] [blame] | 528 | |
Serhiy Storchaka | 7a6915e | 2014-11-27 19:41:47 +0200 | [diff] [blame] | 529 | The JSON format is specified by :rfc:`7159` and by |
| 530 | `ECMA-404 <http://www.ecma-international.org/publications/standards/Ecma-404.htm>`_. |
| 531 | This section details this module's level of compliance with the RFC. |
| 532 | For simplicity, :class:`JSONEncoder` and :class:`JSONDecoder` subclasses, and |
| 533 | parameters other than those explicitly mentioned, are not considered. |
Antoine Pitrou | 331624b | 2012-08-24 19:37:23 +0200 | [diff] [blame] | 534 | |
| 535 | This module does not comply with the RFC in a strict fashion, implementing some |
| 536 | extensions that are valid JavaScript but not valid JSON. In particular: |
| 537 | |
Antoine Pitrou | 331624b | 2012-08-24 19:37:23 +0200 | [diff] [blame] | 538 | - Infinite and NaN number values are accepted and output; |
| 539 | - Repeated names within an object are accepted, and only the value of the last |
| 540 | name-value pair is used. |
| 541 | |
| 542 | Since the RFC permits RFC-compliant parsers to accept input texts that are not |
| 543 | RFC-compliant, this module's deserializer is technically RFC-compliant under |
| 544 | default settings. |
| 545 | |
| 546 | Character Encodings |
| 547 | ^^^^^^^^^^^^^^^^^^^ |
| 548 | |
Serhiy Storchaka | 7a6915e | 2014-11-27 19:41:47 +0200 | [diff] [blame] | 549 | The RFC requires that JSON be represented using either UTF-8, UTF-16, or |
| 550 | UTF-32, with UTF-8 being the recommended default for maximum interoperability. |
Antoine Pitrou | 331624b | 2012-08-24 19:37:23 +0200 | [diff] [blame] | 551 | |
| 552 | As permitted, though not required, by the RFC, this module's serializer sets |
| 553 | *ensure_ascii=True* by default, thus escaping the output so that the resulting |
| 554 | strings only contain ASCII characters. |
| 555 | |
| 556 | Other than the *ensure_ascii* parameter, this module is defined strictly in |
| 557 | terms of conversion between Python objects and |
Serhiy Storchaka | 7a6915e | 2014-11-27 19:41:47 +0200 | [diff] [blame] | 558 | :class:`Unicode strings <str>`, and thus does not otherwise directly address |
| 559 | the issue of character encodings. |
Antoine Pitrou | 331624b | 2012-08-24 19:37:23 +0200 | [diff] [blame] | 560 | |
Serhiy Storchaka | 7a6915e | 2014-11-27 19:41:47 +0200 | [diff] [blame] | 561 | The RFC prohibits adding a byte order mark (BOM) to the start of a JSON text, |
| 562 | and this module's serializer does not add a BOM to its output. |
| 563 | The RFC permits, but does not require, JSON deserializers to ignore an initial |
| 564 | BOM in their input. This module's deserializer raises a :exc:`ValueError` |
| 565 | when an initial BOM is present. |
Antoine Pitrou | 331624b | 2012-08-24 19:37:23 +0200 | [diff] [blame] | 566 | |
Serhiy Storchaka | 7a6915e | 2014-11-27 19:41:47 +0200 | [diff] [blame] | 567 | The RFC does not explicitly forbid JSON strings which contain byte sequences |
| 568 | that don't correspond to valid Unicode characters (e.g. unpaired UTF-16 |
| 569 | surrogates), but it does note that they may cause interoperability problems. |
| 570 | By default, this module accepts and outputs (when present in the original |
Serhiy Storchaka | d3faf43 | 2015-01-18 11:28:37 +0200 | [diff] [blame] | 571 | :class:`str`) code points for such sequences. |
Antoine Pitrou | 331624b | 2012-08-24 19:37:23 +0200 | [diff] [blame] | 572 | |
| 573 | |
| 574 | Infinite and NaN Number Values |
| 575 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 576 | |
| 577 | The RFC does not permit the representation of infinite or NaN number values. |
| 578 | Despite that, by default, this module accepts and outputs ``Infinity``, |
| 579 | ``-Infinity``, and ``NaN`` as if they were valid JSON number literal values:: |
| 580 | |
| 581 | >>> # Neither of these calls raises an exception, but the results are not valid JSON |
| 582 | >>> json.dumps(float('-inf')) |
| 583 | '-Infinity' |
| 584 | >>> json.dumps(float('nan')) |
| 585 | 'NaN' |
| 586 | >>> # Same when deserializing |
| 587 | >>> json.loads('-Infinity') |
| 588 | -inf |
| 589 | >>> json.loads('NaN') |
| 590 | nan |
| 591 | |
| 592 | In the serializer, the *allow_nan* parameter can be used to alter this |
| 593 | behavior. In the deserializer, the *parse_constant* parameter can be used to |
| 594 | alter this behavior. |
| 595 | |
| 596 | |
| 597 | Repeated Names Within an Object |
| 598 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 599 | |
| 600 | The RFC specifies that the names within a JSON object should be unique, but |
Serhiy Storchaka | 7a6915e | 2014-11-27 19:41:47 +0200 | [diff] [blame] | 601 | does not mandate how repeated names in JSON objects should be handled. By |
Antoine Pitrou | 331624b | 2012-08-24 19:37:23 +0200 | [diff] [blame] | 602 | default, this module does not raise an exception; instead, it ignores all but |
| 603 | the last name-value pair for a given name:: |
| 604 | |
| 605 | >>> weird_json = '{"x": 1, "x": 2, "x": 3}' |
| 606 | >>> json.loads(weird_json) |
| 607 | {'x': 3} |
| 608 | |
| 609 | The *object_pairs_hook* parameter can be used to alter this behavior. |
Benjamin Peterson | 940e207 | 2014-03-21 23:17:29 -0500 | [diff] [blame] | 610 | |
Serhiy Storchaka | 7a6915e | 2014-11-27 19:41:47 +0200 | [diff] [blame] | 611 | |
| 612 | Top-level Non-Object, Non-Array Values |
| 613 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 614 | |
| 615 | The old version of JSON specified by the obsolete :rfc:`4627` required that |
| 616 | the top-level value of a JSON text must be either a JSON object or array |
| 617 | (Python :class:`dict` or :class:`list`), and could not be a JSON null, |
| 618 | boolean, number, or string value. :rfc:`7159` removed that restriction, and |
| 619 | this module does not and has never implemented that restriction in either its |
| 620 | serializer or its deserializer. |
| 621 | |
| 622 | Regardless, for maximum interoperability, you may wish to voluntarily adhere |
| 623 | to the restriction yourself. |
| 624 | |
| 625 | |
| 626 | Implementation Limitations |
| 627 | ^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 628 | |
| 629 | Some JSON deserializer implementations may set limits on: |
| 630 | |
| 631 | * the size of accepted JSON texts |
| 632 | * the maximum level of nesting of JSON objects and arrays |
| 633 | * the range and precision of JSON numbers |
| 634 | * the content and maximum length of JSON strings |
| 635 | |
| 636 | This module does not impose any such limits beyond those of the relevant |
| 637 | Python datatypes themselves or the Python interpreter itself. |
| 638 | |
| 639 | When serializing to JSON, beware any such limitations in applications that may |
| 640 | consume your JSON. In particular, it is common for JSON numbers to be |
| 641 | deserialized into IEEE 754 double precision numbers and thus subject to that |
| 642 | representation's range and precision limitations. This is especially relevant |
| 643 | when serializing Python :class:`int` values of extremely large magnitude, or |
| 644 | when serializing instances of "exotic" numerical types such as |
| 645 | :class:`decimal.Decimal`. |
| 646 | |
Benjamin Peterson | 940e207 | 2014-03-21 23:17:29 -0500 | [diff] [blame] | 647 | .. highlight:: bash |
| 648 | |
| 649 | .. _json-commandline: |
| 650 | |
| 651 | Command Line Interface |
| 652 | ---------------------- |
| 653 | |
Terry Jan Reedy | dcb6c88 | 2016-06-22 22:46:34 -0400 | [diff] [blame] | 654 | .. module:: json.tool |
| 655 | :synopsis: A command line to validate and pretty-print JSON. |
| 656 | |
| 657 | **Source code:** :source:`Lib/json/tool.py` |
| 658 | |
| 659 | -------------- |
| 660 | |
Benjamin Peterson | 940e207 | 2014-03-21 23:17:29 -0500 | [diff] [blame] | 661 | The :mod:`json.tool` module provides a simple command line interface to validate |
| 662 | and pretty-print JSON objects. |
| 663 | |
Georg Brandl | 9e7fbde | 2014-09-21 00:38:13 +0200 | [diff] [blame] | 664 | If the optional ``infile`` and ``outfile`` arguments are not |
Benjamin Peterson | 940e207 | 2014-03-21 23:17:29 -0500 | [diff] [blame] | 665 | specified, :attr:`sys.stdin` and :attr:`sys.stdout` will be used respectively:: |
| 666 | |
| 667 | $ echo '{"json": "obj"}' | python -m json.tool |
| 668 | { |
| 669 | "json": "obj" |
| 670 | } |
| 671 | $ echo '{1.2:3.4}' | python -m json.tool |
| 672 | Expecting property name enclosed in double quotes: line 1 column 2 (char 1) |
| 673 | |
Berker Peksag | 39e4c4d | 2014-11-10 09:56:54 +0200 | [diff] [blame] | 674 | .. versionchanged:: 3.5 |
| 675 | The output is now in the same order as the input. Use the |
| 676 | :option:`--sort-keys` option to sort the output of dictionaries |
| 677 | alphabetically by key. |
Benjamin Peterson | 940e207 | 2014-03-21 23:17:29 -0500 | [diff] [blame] | 678 | |
| 679 | Command line options |
| 680 | ^^^^^^^^^^^^^^^^^^^^ |
| 681 | |
Benjamin Peterson | fc8e988 | 2014-04-13 19:52:14 -0400 | [diff] [blame] | 682 | .. cmdoption:: infile |
Benjamin Peterson | 940e207 | 2014-03-21 23:17:29 -0500 | [diff] [blame] | 683 | |
| 684 | The JSON file to be validated or pretty-printed:: |
| 685 | |
| 686 | $ python -m json.tool mp_films.json |
| 687 | [ |
| 688 | { |
| 689 | "title": "And Now for Something Completely Different", |
| 690 | "year": 1971 |
| 691 | }, |
| 692 | { |
| 693 | "title": "Monty Python and the Holy Grail", |
| 694 | "year": 1975 |
| 695 | } |
| 696 | ] |
| 697 | |
Benjamin Peterson | fc8e988 | 2014-04-13 19:52:14 -0400 | [diff] [blame] | 698 | If *infile* is not specified, read from :attr:`sys.stdin`. |
| 699 | |
| 700 | .. cmdoption:: outfile |
Benjamin Peterson | 940e207 | 2014-03-21 23:17:29 -0500 | [diff] [blame] | 701 | |
| 702 | Write the output of the *infile* to the given *outfile*. Otherwise, write it |
| 703 | to :attr:`sys.stdout`. |
| 704 | |
Berker Peksag | 39e4c4d | 2014-11-10 09:56:54 +0200 | [diff] [blame] | 705 | .. cmdoption:: --sort-keys |
| 706 | |
| 707 | Sort the output of dictionaries alphabetically by key. |
| 708 | |
| 709 | .. versionadded:: 3.5 |
| 710 | |
Benjamin Peterson | 940e207 | 2014-03-21 23:17:29 -0500 | [diff] [blame] | 711 | .. cmdoption:: -h, --help |
| 712 | |
| 713 | Show the help message. |
Serhiy Storchaka | 715f01b | 2014-11-27 19:45:31 +0200 | [diff] [blame] | 714 | |
Serhiy Storchaka | 7a6915e | 2014-11-27 19:41:47 +0200 | [diff] [blame] | 715 | |
| 716 | .. rubric:: Footnotes |
| 717 | |
| 718 | .. [#rfc-errata] As noted in `the errata for RFC 7159 |
Serhiy Storchaka | 6dff020 | 2016-05-07 10:49:07 +0300 | [diff] [blame] | 719 | <https://www.rfc-editor.org/errata_search.php?rfc=7159>`_, |
Serhiy Storchaka | 7a6915e | 2014-11-27 19:41:47 +0200 | [diff] [blame] | 720 | JSON permits literal U+2028 (LINE SEPARATOR) and |
| 721 | U+2029 (PARAGRAPH SEPARATOR) characters in strings, whereas JavaScript |
| 722 | (as of ECMAScript Edition 5.1) does not. |