summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Fjson.html
blob: c0d298888d6f65101677554b58cfd1bb0e7be3bb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
 <span id="json-json-encoder-and-decoder"></span><h1>json — JSON encoder and decoder</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/json/__init__.py">Lib/json/__init__.py</a></p>  <p><a class="reference external" href="https://json.org">JSON (JavaScript Object Notation)</a>, specified by <span class="target" id="index-0"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc7159.html"><strong>RFC 7159</strong></a> (which obsoletes <span class="target" id="index-1"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc4627.html"><strong>RFC 4627</strong></a>) and by <a class="reference external" href="https://www.ecma-international.org/publications-and-standards/standards/ecma-404/">ECMA-404</a>, is a lightweight data interchange format inspired by <a class="reference external" href="https://en.wikipedia.org/wiki/JavaScript">JavaScript</a> object literal syntax (although it is not a strict subset of JavaScript <a class="footnote-reference brackets" href="#rfc-errata" id="id1">1</a> ).</p> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>Be cautious when parsing JSON data from untrusted sources. A malicious JSON string may cause the decoder to consume considerable CPU and memory resources. Limiting the size of data to be parsed is recommended.</p> </div> <p><a class="reference internal" href="#module-json" title="json: Encode and decode the JSON format."><code>json</code></a> exposes an API familiar to users of the standard library <a class="reference internal" href="marshal#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code>marshal</code></a> and <a class="reference internal" href="pickle#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code>pickle</code></a> modules.</p> <p>Encoding basic Python object hierarchies:</p> <pre data-language="python">&gt;&gt;&gt; import json
&gt;&gt;&gt; json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
&gt;&gt;&gt; print(json.dumps("\"foo\bar"))
"\"foo\bar"
&gt;&gt;&gt; print(json.dumps('\u1234'))
"\u1234"
&gt;&gt;&gt; print(json.dumps('\\'))
"\\"
&gt;&gt;&gt; print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
{"a": 0, "b": 0, "c": 0}
&gt;&gt;&gt; from io import StringIO
&gt;&gt;&gt; io = StringIO()
&gt;&gt;&gt; json.dump(['streaming API'], io)
&gt;&gt;&gt; io.getvalue()
'["streaming API"]'
</pre> <p>Compact encoding:</p> <pre data-language="python">&gt;&gt;&gt; import json
&gt;&gt;&gt; json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':'))
'[1,2,3,{"4":5,"6":7}]'
</pre> <p>Pretty printing:</p> <pre data-language="python">&gt;&gt;&gt; import json
&gt;&gt;&gt; print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
{
    "4": 5,
    "6": 7
}
</pre> <p>Decoding JSON:</p> <pre data-language="python">&gt;&gt;&gt; import json
&gt;&gt;&gt; json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
['foo', {'bar': ['baz', None, 1.0, 2]}]
&gt;&gt;&gt; json.loads('"\\"foo\\bar"')
'"foo\x08ar'
&gt;&gt;&gt; from io import StringIO
&gt;&gt;&gt; io = StringIO('["streaming API"]')
&gt;&gt;&gt; json.load(io)
['streaming API']
</pre> <p>Specializing JSON object decoding:</p> <pre data-language="python">&gt;&gt;&gt; import json
&gt;&gt;&gt; def as_complex(dct):
...     if '__complex__' in dct:
...         return complex(dct['real'], dct['imag'])
...     return dct
...
&gt;&gt;&gt; json.loads('{"__complex__": true, "real": 1, "imag": 2}',
...     object_hook=as_complex)
(1+2j)
&gt;&gt;&gt; import decimal
&gt;&gt;&gt; json.loads('1.1', parse_float=decimal.Decimal)
Decimal('1.1')
</pre> <p>Extending <a class="reference internal" href="#json.JSONEncoder" title="json.JSONEncoder"><code>JSONEncoder</code></a>:</p> <pre data-language="python">&gt;&gt;&gt; import json
&gt;&gt;&gt; class ComplexEncoder(json.JSONEncoder):
...     def default(self, obj):
...         if isinstance(obj, complex):
...             return [obj.real, obj.imag]
...         # Let the base class default method raise the TypeError
...         return json.JSONEncoder.default(self, obj)
...
&gt;&gt;&gt; json.dumps(2 + 1j, cls=ComplexEncoder)
'[2.0, 1.0]'
&gt;&gt;&gt; ComplexEncoder().encode(2 + 1j)
'[2.0, 1.0]'
&gt;&gt;&gt; list(ComplexEncoder().iterencode(2 + 1j))
['[2.0', ', 1.0', ']']
</pre> <p>Using <a class="reference internal" href="#module-json.tool" title="json.tool: A command line to validate and pretty-print JSON."><code>json.tool</code></a> from the shell to validate and pretty-print:</p> <pre data-language="shell">$ echo '{"json":"obj"}' | python -m json.tool
{
    "json": "obj"
}
$ echo '{1.2:3.4}' | python -m json.tool
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
</pre> <p>See <a class="reference internal" href="#json-commandline"><span class="std std-ref">Command Line Interface</span></a> for detailed documentation.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>JSON is a subset of <a class="reference external" href="https://yaml.org/">YAML</a> 1.2. The JSON produced by this module’s default settings (in particular, the default <em>separators</em> value) is also a subset of YAML 1.0 and 1.1. This module can thus also be used as a YAML serializer.</p> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p>This module’s encoders and decoders preserve input and output order by default. Order is only lost if the underlying containers are unordered.</p> </div> <section id="basic-usage"> <h2>Basic Usage</h2> <dl class="py function"> <dt class="sig sig-object py" id="json.dump">
<code>json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)</code> </dt> <dd>
<p>Serialize <em>obj</em> as a JSON formatted stream to <em>fp</em> (a <code>.write()</code>-supporting <a class="reference internal" href="../glossary#term-file-like-object"><span class="xref std std-term">file-like object</span></a>) using this <a class="reference internal" href="#py-to-json-table"><span class="std std-ref">conversion table</span></a>.</p> <p>If <em>skipkeys</em> is true (default: <code>False</code>), then dict keys that are not of a basic type (<a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>, <a class="reference internal" href="functions#int" title="int"><code>int</code></a>, <a class="reference internal" href="functions#float" title="float"><code>float</code></a>, <a class="reference internal" href="functions#bool" title="bool"><code>bool</code></a>, <code>None</code>) will be skipped instead of raising a <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a>.</p> <p>The <a class="reference internal" href="#module-json" title="json: Encode and decode the JSON format."><code>json</code></a> module always produces <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> objects, not <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> objects. Therefore, <code>fp.write()</code> must support <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> input.</p> <p>If <em>ensure_ascii</em> is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If <em>ensure_ascii</em> is false, these characters will be output as-is.</p> <p>If <em>check_circular</em> is false (default: <code>True</code>), then the circular reference check for container types will be skipped and a circular reference will result in a <a class="reference internal" href="exceptions#RecursionError" title="RecursionError"><code>RecursionError</code></a> (or worse).</p> <p>If <em>allow_nan</em> is false (default: <code>True</code>), then it will be a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> to serialize out of range <a class="reference internal" href="functions#float" title="float"><code>float</code></a> values (<code>nan</code>, <code>inf</code>, <code>-inf</code>) in strict compliance of the JSON specification. If <em>allow_nan</em> is true, their JavaScript equivalents (<code>NaN</code>, <code>Infinity</code>, <code>-Infinity</code>) will be used.</p> <p>If <em>indent</em> is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or <code>""</code> will only insert newlines. <code>None</code> (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If <em>indent</em> is a string (such as <code>"\t"</code>), that string is used to indent each level.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>Allow strings for <em>indent</em> in addition to integers.</p> </div> <p>If specified, <em>separators</em> should be an <code>(item_separator, key_separator)</code> tuple. The default is <code>(', ', ': ')</code> if <em>indent</em> is <code>None</code> and <code>(',', ': ')</code> otherwise. To get the most compact JSON representation, you should specify <code>(',', ':')</code> to eliminate whitespace.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Use <code>(',', ': ')</code> as default if <em>indent</em> is not <code>None</code>.</p> </div> <p>If specified, <em>default</em> should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a>. If not specified, <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> is raised.</p> <p>If <em>sort_keys</em> is true (default: <code>False</code>), then the output of dictionaries will be sorted by key.</p> <p>To use a custom <a class="reference internal" href="#json.JSONEncoder" title="json.JSONEncoder"><code>JSONEncoder</code></a> subclass (e.g. one that overrides the <a class="reference internal" href="#json.JSONEncoder.default" title="json.JSONEncoder.default"><code>default()</code></a> method to serialize additional types), specify it with the <em>cls</em> kwarg; otherwise <a class="reference internal" href="#json.JSONEncoder" title="json.JSONEncoder"><code>JSONEncoder</code></a> is used.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>All optional parameters are now <a class="reference internal" href="../glossary#keyword-only-parameter"><span class="std std-ref">keyword-only</span></a>.</p> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Unlike <a class="reference internal" href="pickle#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code>pickle</code></a> and <a class="reference internal" href="marshal#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code>marshal</code></a>, JSON is not a framed protocol, so trying to serialize multiple objects with repeated calls to <a class="reference internal" href="#json.dump" title="json.dump"><code>dump()</code></a> using the same <em>fp</em> will result in an invalid JSON file.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="json.dumps">
<code>json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)</code> </dt> <dd>
<p>Serialize <em>obj</em> to a JSON formatted <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> using this <a class="reference internal" href="#py-to-json-table"><span class="std std-ref">conversion table</span></a>. The arguments have the same meaning as in <a class="reference internal" href="#json.dump" title="json.dump"><code>dump()</code></a>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Keys in key/value pairs of JSON are always of the type <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>. When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, <code>loads(dumps(x)) != x</code> if x has non-string keys.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="json.load">
<code>json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)</code> </dt> <dd>
<p>Deserialize <em>fp</em> (a <code>.read()</code>-supporting <a class="reference internal" href="../glossary#term-text-file"><span class="xref std std-term">text file</span></a> or <a class="reference internal" href="../glossary#term-binary-file"><span class="xref std std-term">binary file</span></a> containing a JSON document) to a Python object using this <a class="reference internal" href="#json-to-py-table"><span class="std std-ref">conversion table</span></a>.</p> <p><em>object_hook</em> is an optional function that will be called with the result of any object literal decoded (a <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a>). The return value of <em>object_hook</em> will be used instead of the <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a>. This feature can be used to implement custom decoders (e.g. <a class="reference external" href="https://www.jsonrpc.org">JSON-RPC</a> class hinting).</p> <p><em>object_pairs_hook</em> is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of <em>object_pairs_hook</em> will be used instead of the <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a>. This feature can be used to implement custom decoders. If <em>object_hook</em> is also defined, the <em>object_pairs_hook</em> takes priority.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.1: </span>Added support for <em>object_pairs_hook</em>.</p> </div> <p><em>parse_float</em>, if specified, will be called with the string of every JSON float to be decoded. By default, this is equivalent to <code>float(num_str)</code>. This can be used to use another datatype or parser for JSON floats (e.g. <a class="reference internal" href="decimal#decimal.Decimal" title="decimal.Decimal"><code>decimal.Decimal</code></a>).</p> <p><em>parse_int</em>, if specified, will be called with the string of every JSON int to be decoded. By default, this is equivalent to <code>int(num_str)</code>. This can be used to use another datatype or parser for JSON integers (e.g. <a class="reference internal" href="functions#float" title="float"><code>float</code></a>).</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>The default <em>parse_int</em> of <a class="reference internal" href="functions#int" title="int"><code>int()</code></a> now limits the maximum length of the integer string via the interpreter’s <a class="reference internal" href="stdtypes#int-max-str-digits"><span class="std std-ref">integer string conversion length limitation</span></a> to help avoid denial of service attacks.</p> </div> <p><em>parse_constant</em>, if specified, will be called with one of the following strings: <code>'-Infinity'</code>, <code>'Infinity'</code>, <code>'NaN'</code>. This can be used to raise an exception if invalid JSON numbers are encountered.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.1: </span><em>parse_constant</em> doesn’t get called on ‘null’, ‘true’, ‘false’ anymore.</p> </div> <p>To use a custom <a class="reference internal" href="#json.JSONDecoder" title="json.JSONDecoder"><code>JSONDecoder</code></a> subclass, specify it with the <code>cls</code> kwarg; otherwise <a class="reference internal" href="#json.JSONDecoder" title="json.JSONDecoder"><code>JSONDecoder</code></a> is used. Additional keyword arguments will be passed to the constructor of the class.</p> <p>If the data being deserialized is not a valid JSON document, a <a class="reference internal" href="#json.JSONDecodeError" title="json.JSONDecodeError"><code>JSONDecodeError</code></a> will be raised.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>All optional parameters are now <a class="reference internal" href="../glossary#keyword-only-parameter"><span class="std std-ref">keyword-only</span></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span><em>fp</em> can now be a <a class="reference internal" href="../glossary#term-binary-file"><span class="xref std std-term">binary file</span></a>. The input encoding should be UTF-8, UTF-16 or UTF-32.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="json.loads">
<code>json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)</code> </dt> <dd>
<p>Deserialize <em>s</em> (a <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>, <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> or <a class="reference internal" href="stdtypes#bytearray" title="bytearray"><code>bytearray</code></a> instance containing a JSON document) to a Python object using this <a class="reference internal" href="#json-to-py-table"><span class="std std-ref">conversion table</span></a>.</p> <p>The other arguments have the same meaning as in <a class="reference internal" href="#json.load" title="json.load"><code>load()</code></a>.</p> <p>If the data being deserialized is not a valid JSON document, a <a class="reference internal" href="#json.JSONDecodeError" title="json.JSONDecodeError"><code>JSONDecodeError</code></a> will be raised.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span><em>s</em> can now be of type <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> or <a class="reference internal" href="stdtypes#bytearray" title="bytearray"><code>bytearray</code></a>. The input encoding should be UTF-8, UTF-16 or UTF-32.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>The keyword argument <em>encoding</em> has been removed.</p> </div> </dd>
</dl> </section> <section id="encoders-and-decoders"> <h2>Encoders and Decoders</h2> <dl class="py class"> <dt class="sig sig-object py" id="json.JSONDecoder">
<code>class json.JSONDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)</code> </dt> <dd>
<p>Simple JSON decoder.</p> <p>Performs the following translations in decoding by default:</p> <table class="docutils align-default" id="json-to-py-table">  <thead> <tr>
<th class="head"><p>JSON</p></th> <th class="head"><p>Python</p></th> </tr> </thead>  <tr>
<td><p>object</p></td> <td><p>dict</p></td> </tr> <tr>
<td><p>array</p></td> <td><p>list</p></td> </tr> <tr>
<td><p>string</p></td> <td><p>str</p></td> </tr> <tr>
<td><p>number (int)</p></td> <td><p>int</p></td> </tr> <tr>
<td><p>number (real)</p></td> <td><p>float</p></td> </tr> <tr>
<td><p>true</p></td> <td><p>True</p></td> </tr> <tr>
<td><p>false</p></td> <td><p>False</p></td> </tr> <tr>
<td><p>null</p></td> <td><p>None</p></td> </tr>  </table> <p>It also understands <code>NaN</code>, <code>Infinity</code>, and <code>-Infinity</code> as their corresponding <code>float</code> values, which is outside the JSON spec.</p> <p><em>object_hook</em>, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a>. This can be used to provide custom deserializations (e.g. to support <a class="reference external" href="https://www.jsonrpc.org">JSON-RPC</a> class hinting).</p> <p><em>object_pairs_hook</em>, if specified will be called with the result of every JSON object decoded with an ordered list of pairs. The return value of <em>object_pairs_hook</em> will be used instead of the <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a>. This feature can be used to implement custom decoders. If <em>object_hook</em> is also defined, the <em>object_pairs_hook</em> takes priority.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.1: </span>Added support for <em>object_pairs_hook</em>.</p> </div> <p><em>parse_float</em>, if specified, will be called with the string of every JSON float to be decoded. By default, this is equivalent to <code>float(num_str)</code>. This can be used to use another datatype or parser for JSON floats (e.g. <a class="reference internal" href="decimal#decimal.Decimal" title="decimal.Decimal"><code>decimal.Decimal</code></a>).</p> <p><em>parse_int</em>, if specified, will be called with the string of every JSON int to be decoded. By default, this is equivalent to <code>int(num_str)</code>. This can be used to use another datatype or parser for JSON integers (e.g. <a class="reference internal" href="functions#float" title="float"><code>float</code></a>).</p> <p><em>parse_constant</em>, if specified, will be called with one of the following strings: <code>'-Infinity'</code>, <code>'Infinity'</code>, <code>'NaN'</code>. This can be used to raise an exception if invalid JSON numbers are encountered.</p> <p>If <em>strict</em> is false (<code>True</code> is the default), then control characters will be allowed inside strings. Control characters in this context are those with character codes in the 0–31 range, including <code>'\t'</code> (tab), <code>'\n'</code>, <code>'\r'</code> and <code>'\0'</code>.</p> <p>If the data being deserialized is not a valid JSON document, a <a class="reference internal" href="#json.JSONDecodeError" title="json.JSONDecodeError"><code>JSONDecodeError</code></a> will be raised.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>All parameters are now <a class="reference internal" href="../glossary#keyword-only-parameter"><span class="std std-ref">keyword-only</span></a>.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="json.JSONDecoder.decode">
<code>decode(s)</code> </dt> <dd>
<p>Return the Python representation of <em>s</em> (a <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> instance containing a JSON document).</p> <p><a class="reference internal" href="#json.JSONDecodeError" title="json.JSONDecodeError"><code>JSONDecodeError</code></a> will be raised if the given JSON document is not valid.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="json.JSONDecoder.raw_decode">
<code>raw_decode(s)</code> </dt> <dd>
<p>Decode a JSON document from <em>s</em> (a <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> beginning with a JSON document) and return a 2-tuple of the Python representation and the index in <em>s</em> where the document ended.</p> <p>This can be used to decode a JSON document from a string that may have extraneous data at the end.</p> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="json.JSONEncoder">
<code>class json.JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)</code> </dt> <dd>
<p>Extensible JSON encoder for Python data structures.</p> <p>Supports the following objects and types by default:</p> <table class="docutils align-default" id="py-to-json-table">  <thead> <tr>
<th class="head"><p>Python</p></th> <th class="head"><p>JSON</p></th> </tr> </thead>  <tr>
<td><p>dict</p></td> <td><p>object</p></td> </tr> <tr>
<td><p>list, tuple</p></td> <td><p>array</p></td> </tr> <tr>
<td><p>str</p></td> <td><p>string</p></td> </tr> <tr>
<td><p>int, float, int- &amp; float-derived Enums</p></td> <td><p>number</p></td> </tr> <tr>
<td><p>True</p></td> <td><p>true</p></td> </tr> <tr>
<td><p>False</p></td> <td><p>false</p></td> </tr> <tr>
<td><p>None</p></td> <td><p>null</p></td> </tr>  </table> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Added support for int- and float-derived Enum classes.</p> </div> <p>To extend this to recognize other objects, subclass and implement a <a class="reference internal" href="#json.JSONEncoder.default" title="json.JSONEncoder.default"><code>default()</code></a> method with another method that returns a serializable object for <code>o</code> if possible, otherwise it should call the superclass implementation (to raise <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a>).</p> <p>If <em>skipkeys</em> is false (the default), a <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> will be raised when trying to encode keys that are not <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>, <a class="reference internal" href="functions#int" title="int"><code>int</code></a>, <a class="reference internal" href="functions#float" title="float"><code>float</code></a> or <code>None</code>. If <em>skipkeys</em> is true, such items are simply skipped.</p> <p>If <em>ensure_ascii</em> is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If <em>ensure_ascii</em> is false, these characters will be output as-is.</p> <p>If <em>check_circular</em> is true (the default), then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause a <a class="reference internal" href="exceptions#RecursionError" title="RecursionError"><code>RecursionError</code></a>). Otherwise, no such check takes place.</p> <p>If <em>allow_nan</em> is true (the default), then <code>NaN</code>, <code>Infinity</code>, and <code>-Infinity</code> will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> to encode such floats.</p> <p>If <em>sort_keys</em> is true (default: <code>False</code>), then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.</p> <p>If <em>indent</em> is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or <code>""</code> will only insert newlines. <code>None</code> (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If <em>indent</em> is a string (such as <code>"\t"</code>), that string is used to indent each level.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>Allow strings for <em>indent</em> in addition to integers.</p> </div> <p>If specified, <em>separators</em> should be an <code>(item_separator, key_separator)</code> tuple. The default is <code>(', ', ': ')</code> if <em>indent</em> is <code>None</code> and <code>(',', ': ')</code> otherwise. To get the most compact JSON representation, you should specify <code>(',', ':')</code> to eliminate whitespace.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Use <code>(',', ': ')</code> as default if <em>indent</em> is not <code>None</code>.</p> </div> <p>If specified, <em>default</em> should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a>. If not specified, <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> is raised.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>All parameters are now <a class="reference internal" href="../glossary#keyword-only-parameter"><span class="std std-ref">keyword-only</span></a>.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="json.JSONEncoder.default">
<code>default(o)</code> </dt> <dd>
<p>Implement this method in a subclass such that it returns a serializable object for <em>o</em>, or calls the base implementation (to raise a <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a>).</p> <p>For example, to support arbitrary iterators, you could implement <a class="reference internal" href="#json.JSONEncoder.default" title="json.JSONEncoder.default"><code>default()</code></a> like this:</p> <pre data-language="python">def default(self, o):
   try:
       iterable = iter(o)
   except TypeError:
       pass
   else:
       return list(iterable)
   # Let the base class default method raise the TypeError
   return json.JSONEncoder.default(self, o)
</pre> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="json.JSONEncoder.encode">
<code>encode(o)</code> </dt> <dd>
<p>Return a JSON string representation of a Python data structure, <em>o</em>. For example:</p> <pre data-language="python">&gt;&gt;&gt; json.JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
</pre> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="json.JSONEncoder.iterencode">
<code>iterencode(o)</code> </dt> <dd>
<p>Encode the given object, <em>o</em>, and yield each string representation as available. For example:</p> <pre data-language="python">for chunk in json.JSONEncoder().iterencode(bigobject):
    mysocket.write(chunk)
</pre> </dd>
</dl> </dd>
</dl> </section> <section id="exceptions"> <h2>Exceptions</h2> <dl class="py exception"> <dt class="sig sig-object py" id="json.JSONDecodeError">
<code>exception json.JSONDecodeError(msg, doc, pos)</code> </dt> <dd>
<p>Subclass of <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> with the following additional attributes:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="json.JSONDecodeError.msg">
<code>msg</code> </dt> <dd>
<p>The unformatted error message.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="json.JSONDecodeError.doc">
<code>doc</code> </dt> <dd>
<p>The JSON document being parsed.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="json.JSONDecodeError.pos">
<code>pos</code> </dt> <dd>
<p>The start index of <em>doc</em> where parsing failed.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="json.JSONDecodeError.lineno">
<code>lineno</code> </dt> <dd>
<p>The line corresponding to <em>pos</em>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="json.JSONDecodeError.colno">
<code>colno</code> </dt> <dd>
<p>The column corresponding to <em>pos</em>.</p> </dd>
</dl> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd>
</dl> </section> <section id="standard-compliance-and-interoperability"> <h2>Standard Compliance and Interoperability</h2> <p>The JSON format is specified by <span class="target" id="index-2"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc7159.html"><strong>RFC 7159</strong></a> and by <a class="reference external" href="https://www.ecma-international.org/publications-and-standards/standards/ecma-404/">ECMA-404</a>. This section details this module’s level of compliance with the RFC. For simplicity, <a class="reference internal" href="#json.JSONEncoder" title="json.JSONEncoder"><code>JSONEncoder</code></a> and <a class="reference internal" href="#json.JSONDecoder" title="json.JSONDecoder"><code>JSONDecoder</code></a> subclasses, and parameters other than those explicitly mentioned, are not considered.</p> <p>This module does not comply with the RFC in a strict fashion, implementing some extensions that are valid JavaScript but not valid JSON. In particular:</p> <ul class="simple"> <li>Infinite and NaN number values are accepted and output;</li> <li>Repeated names within an object are accepted, and only the value of the last name-value pair is used.</li> </ul> <p>Since the RFC permits RFC-compliant parsers to accept input texts that are not RFC-compliant, this module’s deserializer is technically RFC-compliant under default settings.</p> <section id="character-encodings"> <h3>Character Encodings</h3> <p>The RFC requires that JSON be represented using either UTF-8, UTF-16, or UTF-32, with UTF-8 being the recommended default for maximum interoperability.</p> <p>As permitted, though not required, by the RFC, this module’s serializer sets <em>ensure_ascii=True</em> by default, thus escaping the output so that the resulting strings only contain ASCII characters.</p> <p>Other than the <em>ensure_ascii</em> parameter, this module is defined strictly in terms of conversion between Python objects and <a class="reference internal" href="stdtypes#str" title="str"><code>Unicode strings</code></a>, and thus does not otherwise directly address the issue of character encodings.</p> <p>The RFC prohibits adding a byte order mark (BOM) to the start of a JSON text, and this module’s serializer does not add a BOM to its output. The RFC permits, but does not require, JSON deserializers to ignore an initial BOM in their input. This module’s deserializer raises a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> when an initial BOM is present.</p> <p>The RFC does not explicitly forbid JSON strings which contain byte sequences that don’t correspond to valid Unicode characters (e.g. unpaired UTF-16 surrogates), but it does note that they may cause interoperability problems. By default, this module accepts and outputs (when present in the original <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>) code points for such sequences.</p> </section> <section id="infinite-and-nan-number-values"> <h3>Infinite and NaN Number Values</h3> <p>The RFC does not permit the representation of infinite or NaN number values. Despite that, by default, this module accepts and outputs <code>Infinity</code>, <code>-Infinity</code>, and <code>NaN</code> as if they were valid JSON number literal values:</p> <pre data-language="python">&gt;&gt;&gt; # Neither of these calls raises an exception, but the results are not valid JSON
&gt;&gt;&gt; json.dumps(float('-inf'))
'-Infinity'
&gt;&gt;&gt; json.dumps(float('nan'))
'NaN'
&gt;&gt;&gt; # Same when deserializing
&gt;&gt;&gt; json.loads('-Infinity')
-inf
&gt;&gt;&gt; json.loads('NaN')
nan
</pre> <p>In the serializer, the <em>allow_nan</em> parameter can be used to alter this behavior. In the deserializer, the <em>parse_constant</em> parameter can be used to alter this behavior.</p> </section> <section id="repeated-names-within-an-object"> <h3>Repeated Names Within an Object</h3> <p>The RFC specifies that the names within a JSON object should be unique, but does not mandate how repeated names in JSON objects should be handled. By default, this module does not raise an exception; instead, it ignores all but the last name-value pair for a given name:</p> <pre data-language="python">&gt;&gt;&gt; weird_json = '{"x": 1, "x": 2, "x": 3}'
&gt;&gt;&gt; json.loads(weird_json)
{'x': 3}
</pre> <p>The <em>object_pairs_hook</em> parameter can be used to alter this behavior.</p> </section> <section id="top-level-non-object-non-array-values"> <h3>Top-level Non-Object, Non-Array Values</h3> <p>The old version of JSON specified by the obsolete <span class="target" id="index-3"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc4627.html"><strong>RFC 4627</strong></a> required that the top-level value of a JSON text must be either a JSON object or array (Python <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> or <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a>), and could not be a JSON null, boolean, number, or string value. <span class="target" id="index-4"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc7159.html"><strong>RFC 7159</strong></a> removed that restriction, and this module does not and has never implemented that restriction in either its serializer or its deserializer.</p> <p>Regardless, for maximum interoperability, you may wish to voluntarily adhere to the restriction yourself.</p> </section> <section id="implementation-limitations"> <h3>Implementation Limitations</h3> <p>Some JSON deserializer implementations may set limits on:</p> <ul class="simple"> <li>the size of accepted JSON texts</li> <li>the maximum level of nesting of JSON objects and arrays</li> <li>the range and precision of JSON numbers</li> <li>the content and maximum length of JSON strings</li> </ul> <p>This module does not impose any such limits beyond those of the relevant Python datatypes themselves or the Python interpreter itself.</p> <p>When serializing to JSON, beware any such limitations in applications that may consume your JSON. In particular, it is common for JSON numbers to be deserialized into IEEE 754 double precision numbers and thus subject to that representation’s range and precision limitations. This is especially relevant when serializing Python <a class="reference internal" href="functions#int" title="int"><code>int</code></a> values of extremely large magnitude, or when serializing instances of “exotic” numerical types such as <a class="reference internal" href="decimal#decimal.Decimal" title="decimal.Decimal"><code>decimal.Decimal</code></a>.</p> </section> </section> <section id="module-json.tool"> <span id="command-line-interface"></span><span id="json-commandline"></span><h2>Command Line Interface</h2> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/json/tool.py">Lib/json/tool.py</a></p>  <p>The <a class="reference internal" href="#module-json.tool" title="json.tool: A command line to validate and pretty-print JSON."><code>json.tool</code></a> module provides a simple command line interface to validate and pretty-print JSON objects.</p> <p>If the optional <code>infile</code> and <code>outfile</code> arguments are not specified, <a class="reference internal" href="sys#sys.stdin" title="sys.stdin"><code>sys.stdin</code></a> and <a class="reference internal" href="sys#sys.stdout" title="sys.stdout"><code>sys.stdout</code></a> will be used respectively:</p> <pre data-language="shell">$ echo '{"json": "obj"}' | python -m json.tool
{
    "json": "obj"
}
$ echo '{1.2:3.4}' | python -m json.tool
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>The output is now in the same order as the input. Use the <a class="reference internal" href="#cmdoption-json.tool-sort-keys"><code>--sort-keys</code></a> option to sort the output of dictionaries alphabetically by key.</p> </div> <section id="command-line-options"> <h3>Command line options</h3> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-json.tool-arg-infile">
<code>infile</code> </dt> <dd>
<p>The JSON file to be validated or pretty-printed:</p> <pre data-language="shell">$ python -m json.tool mp_films.json
[
    {
        "title": "And Now for Something Completely Different",
        "year": 1971
    },
    {
        "title": "Monty Python and the Holy Grail",
        "year": 1975
    }
]
</pre> <p>If <em>infile</em> is not specified, read from <a class="reference internal" href="sys#sys.stdin" title="sys.stdin"><code>sys.stdin</code></a>.</p> </dd>
</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-json.tool-arg-outfile">
<code>outfile</code> </dt> <dd>
<p>Write the output of the <em>infile</em> to the given <em>outfile</em>. Otherwise, write it to <a class="reference internal" href="sys#sys.stdout" title="sys.stdout"><code>sys.stdout</code></a>.</p> </dd>
</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-json.tool-sort-keys">
<code>--sort-keys</code> </dt> <dd>
<p>Sort the output of dictionaries alphabetically by key.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd>
</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-json.tool-no-ensure-ascii">
<code>--no-ensure-ascii</code> </dt> <dd>
<p>Disable escaping of non-ascii characters, see <a class="reference internal" href="#json.dumps" title="json.dumps"><code>json.dumps()</code></a> for more information.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.9.</span></p> </div> </dd>
</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-json.tool-json-lines">
<code>--json-lines</code> </dt> <dd>
<p>Parse every input line as separate JSON object.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-json.tool-indent">
<code>--indent, --tab, --no-indent, --compact</code> </dt> <dd>
<p>Mutually exclusive options for whitespace control.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.9.</span></p> </div> </dd>
</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-json.tool-h">
<code>-h, --help</code> </dt> <dd>
<p>Show the help message.</p> </dd>
</dl> <h4 class="rubric">Footnotes</h4> <dl class="footnote brackets"> <dt class="label" id="rfc-errata">
<code>1</code> </dt> <dd>
<p>As noted in <a class="reference external" href="https://www.rfc-editor.org/errata_search.php?rfc=7159">the errata for RFC 7159</a>, JSON permits literal U+2028 (LINE SEPARATOR) and U+2029 (PARAGRAPH SEPARATOR) characters in strings, whereas JavaScript (as of ECMAScript Edition 5.1) does not.</p> </dd> </dl> </section> </section> <div class="_attribution">
  <p class="_attribution-p">
    &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
    <a href="https://docs.python.org/3.12/library/json.html" class="_attribution-link">https://docs.python.org/3.12/library/json.html</a>
  </p>
</div>