Lines Matching full:json
1 :mod:`json` --- JSON encoder and decoder
4 .. module:: json
5 :synopsis: Encode and decode the JSON format.
10 **Source code:** :source:`Lib/json/__init__.py`
14 `JSON (JavaScript Object Notation) <https://json.org>`_, specified by
22 Be cautious when parsing JSON data from untrusted sources. A malicious
23 JSON string may cause the decoder to consume considerable CPU and memory
26 :mod:`json` exposes an API familiar to users of the standard library
31 >>> import json
32 >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
34 >>> print(json.dumps("\"foo\bar"))
36 >>> print(json.dumps('\u1234'))
38 >>> print(json.dumps('\\'))
40 >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
44 >>> json.dump(['streaming API'], io)
50 >>> import json
51 >>> json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':'))
56 >>> import json
57 >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
63 Decoding JSON::
65 >>> import json
66 >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
68 >>> json.loads('"\\"foo\\bar"')
72 >>> json.load(io)
75 Specializing JSON object decoding::
77 >>> import json
83 >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
87 >>> json.loads('1.1', parse_float=decimal.Decimal)
92 >>> import json
93 >>> class ComplexEncoder(json.JSONEncoder):
98 ... return json.JSONEncoder.default(self, obj)
100 >>> json.dumps(2 + 1j, cls=ComplexEncoder)
108 Using :mod:`json.tool` from the shell to validate and pretty-print:
112 $ echo '{"json":"obj"}' | python -m json.tool
114 "json": "obj"
116 $ echo '{1.2:3.4}' | python -m json.tool
119 See :ref:`json-commandline` for detailed documentation.
123 JSON is a subset of `YAML <https://yaml.org/>`_ 1.2. The JSON produced by
142 Serialize *obj* as a JSON formatted stream to *fp* (a ``.write()``-supporting
144 <py-to-json-table>`.
150 The :mod:`json` module always produces :class:`str` objects, not
164 ``inf``, ``-inf``) in strict compliance of the JSON specification.
168 If *indent* is a non-negative integer or string, then JSON array elements and
180 ``(',', ': ')`` otherwise. To get the most compact JSON representation,
187 can't otherwise be serialized. It should return a JSON encodable version of
203 Unlike :mod:`pickle` and :mod:`marshal`, JSON is not a framed protocol,
205 :func:`dump` using the same *fp* will result in an invalid JSON file.
212 Serialize *obj* to a JSON formatted :class:`str` using this :ref:`conversion
213 table <py-to-json-table>`. The arguments have the same meaning as in
218 Keys in key/value pairs of JSON are always of the type :class:`str`. When
219 a dictionary is converted into JSON, all the keys of the dictionary are
221 into JSON and then back into a dictionary, the dictionary may not equal
228 :term:`binary file` containing a JSON document) to a Python object using
229 this :ref:`conversion table <json-to-py-table>`.
234 to implement custom decoders (e.g. `JSON-RPC <https://www.jsonrpc.org>`_
246 *parse_float*, if specified, will be called with the string of every JSON
248 This can be used to use another datatype or parser for JSON floats
251 *parse_int*, if specified, will be called with the string of every JSON int
253 be used to use another datatype or parser for JSON integers
264 This can be used to raise an exception if invalid JSON numbers
274 If the data being deserialized is not a valid JSON document, a
287 instance containing a JSON document) to a Python object using this
288 :ref:`conversion table <json-to-py-table>`.
292 If the data being deserialized is not a valid JSON document, a
308 Simple JSON decoder.
315 | JSON | Python |
335 corresponding ``float`` values, which is outside the JSON spec.
337 *object_hook*, if specified, will be called with the result of every JSON
340 support `JSON-RPC <https://www.jsonrpc.org>`_ class hinting).
343 JSON object decoded with an ordered list of pairs. The return value of
351 *parse_float*, if specified, will be called with the string of every JSON
353 This can be used to use another datatype or parser for JSON floats
356 *parse_int*, if specified, will be called with the string of every JSON int
358 be used to use another datatype or parser for JSON integers
363 This can be used to raise an exception if invalid JSON numbers
371 If the data being deserialized is not a valid JSON document, a
380 containing a JSON document).
382 :exc:`JSONDecodeError` will be raised if the given JSON document is not
387 Decode a JSON document from *s* (a :class:`str` beginning with a
388 JSON document) and return a 2-tuple of the Python representation
391 This can be used to decode a JSON document from a string that may have
397 Extensible JSON encoder for Python data structures.
401 .. _py-to-json-table:
404 | Python | JSON |
443 ``-Infinity`` will be encoded as such. This behavior is not JSON
450 JSON serializations can be compared on a day-to-day basis.
452 If *indent* is a non-negative integer or string, then JSON array elements and
464 ``(',', ': ')`` otherwise. To get the most compact JSON representation,
471 can't otherwise be serialized. It should return a JSON encodable version of
496 return json.JSONEncoder.default(self, o)
501 Return a JSON string representation of a Python data structure, *o*. For
504 >>> json.JSONEncoder().encode({"foo": ["bar", "baz"]})
513 for chunk in json.JSONEncoder().iterencode(bigobject):
530 The JSON document being parsed.
550 The JSON format is specified by :rfc:`7159` and by
557 extensions that are valid JavaScript but not valid JSON. In particular:
570 The RFC requires that JSON be represented using either UTF-8, UTF-16, or
582 The RFC prohibits adding a byte order mark (BOM) to the start of a JSON text,
584 The RFC permits, but does not require, JSON deserializers to ignore an initial
588 The RFC does not explicitly forbid JSON strings which contain byte sequences
600 ``-Infinity``, and ``NaN`` as if they were valid JSON number literal values::
602 >>> # Neither of these calls raises an exception, but the results are not valid JSON
603 >>> json.dumps(float('-inf'))
605 >>> json.dumps(float('nan'))
608 >>> json.loads('-Infinity')
610 >>> json.loads('NaN')
621 The RFC specifies that the names within a JSON object should be unique, but
622 does not mandate how repeated names in JSON objects should be handled. By
627 >>> json.loads(weird_json)
636 The old version of JSON specified by the obsolete :rfc:`4627` required that
637 the top-level value of a JSON text must be either a JSON object or array
638 (Python :class:`dict` or :class:`list`), and could not be a JSON null,
650 Some JSON deserializer implementations may set limits on:
652 * the size of accepted JSON texts
653 * the maximum level of nesting of JSON objects and arrays
654 * the range and precision of JSON numbers
655 * the content and maximum length of JSON strings
660 When serializing to JSON, beware any such limitations in applications that may
661 consume your JSON. In particular, it is common for JSON numbers to be
670 .. program:: json.tool
675 .. module:: json.tool
676 :synopsis: A command line to validate and pretty-print JSON.
678 **Source code:** :source:`Lib/json/tool.py`
682 The :mod:`json.tool` module provides a simple command line interface to validate
683 and pretty-print JSON objects.
690 $ echo '{"json": "obj"}' | python -m json.tool
692 "json": "obj"
694 $ echo '{1.2:3.4}' | python -m json.tool
708 The JSON file to be validated or pretty-printed:
712 $ python -m json.tool mp_films.json
739 Disable escaping of non-ascii characters, see :func:`json.dumps` for more information.
743 .. cmdoption:: --json-lines
745 Parse every input line as separate JSON object.
764 JSON permits literal U+2028 (LINE SEPARATOR) and