Teks sumber — English
Terjemahan — Bahasa Indonesia
`JSON (JavaScript Object Notation) <https://json.org>`_, specified by :rfc:`7159` (which obsoletes :rfc:`4627`) and by `ECMA-404 <https://ecma-international.org/publications-and-standards/standards/ecma-404/>`_, is a lightweight data interchange format inspired by `JavaScript <https://en.wikipedia.org/wiki/JavaScript>`_ object literal syntax (although it is not a strict subset of JavaScript [#rfc-errata]_ ).
The term "object" in the context of JSON processing in Python can be ambiguous. All values in Python are objects. In JSON, an object refers to any data wrapped in curly braces, similar to a Python dictionary.
Encoding basic Python object hierarchies::
Hierarki penyandian objek Python dasar::
Customizing JSON object encoding::
>>> import json
>>> def custom_json(obj):
... if isinstance(obj, complex):
... return {'__complex__': True, 'real': obj.real, 'imag': obj.imag}
... raise TypeError(f'Cannot serialize object of {type(obj)}')
...
>>> json.dumps(1 + 2j, default=custom_json)
'{"__complex__": true, "real": 1.0, "imag": 2.0}'
Customizing JSON object decoding::
>>> import json
>>> def as_complex(dct):
... if '__complex__' in dct:
... return complex(dct['real'], dct['imag'])
... return dct
...
>>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
... object_hook=as_complex)
(1+2j)
>>> import decimal
>>> json.loads('1.1', parse_float=decimal.Decimal)
Decimal('1.1')
>>> json.loads('{"name": "point", "coords": [[1, 2], [3, 4]]}',
... array_hook=tuple)
{'name': 'point', 'coords': ((1, 2), (3, 4))}
>>> json.loads('{"name": "point", "coords": [1, 2]}',
... object_pairs_hook=frozendict, array_hook=tuple)
frozendict({'name': 'point', 'coords': (1, 2)})
Serialize *obj* as a JSON formatted stream to *fp* (a ``.write()``-supporting :term:`file-like object`) using this :ref:`Python-to-JSON conversion table <py-to-json-table>`.
Unlike :mod:`pickle` and :mod:`marshal`, JSON is not a framed protocol, so trying to serialize multiple objects with repeated calls to :func:`dump` using the same *fp* will result in an invalid JSON file.
The Python object to be serialized.
The file-like object *obj* will be serialized to. The :mod:`!json` module always produces :class:`str` objects, not :class:`bytes` objects, therefore ``fp.write()`` must support :class:`str` input.
If a positive integer or string, JSON array elements and object members will be pretty-printed with that indent level. A positive integer indents that many spaces per level; a string (such as ``"\t"``) is used to indent each level. If zero, negative, or ``""`` (the empty string), only newlines are inserted. If ``None`` (the default), no newlines are inserted.
A function that is called for objects that can't otherwise be serialized. It should return a JSON encodable version of the object or raise a :exc:`TypeError`. If ``None`` (the default), :exc:`!TypeError` is raised.
Deserialize *fp* to a Python object using the :ref:`JSON-to-Python conversion table <json-to-py-table>`.
If set, a function that is called with the result of any JSON object literal decoded (a :class:`dict`). The return value of this function will be used instead of the :class:`dict`. This feature can be used to implement custom decoders, for example `JSON-RPC <https://www.jsonrpc.org>`_ class hinting. Default ``None``.
If set, a function that is called with the result of any JSON object literal decoded with an ordered list of pairs. The return value of this function will be used instead of the :class:`dict`. This feature can be used to implement custom decoders. If *object_hook* is also set, *object_pairs_hook* takes priority. Default ``None``.
Added the optional *object_pairs_hook* parameter.
Identical to :func:`load`, but instead of a file-like object, deserialize *s* (a :class:`str`, :class:`bytes` or :class:`bytearray` instance containing a JSON document) to a Python object using this :ref:`conversion table <json-to-py-table>`.
object
objek
*object_hook* is an optional function that will be called with the result of every JSON object decoded and its return value will be used in place of the given :class:`dict`. This can be used to provide custom deserializations (e.g. to support `JSON-RPC <https://www.jsonrpc.org>`_ class hinting).
*object_pairs_hook* is an optional function that will be called with the result of every JSON object decoded with an ordered list of pairs. The return value of *object_pairs_hook* will be used instead of the :class:`dict`. This feature can be used to implement custom decoders. If *object_hook* is also defined, the *object_pairs_hook* takes priority.
Added support for *object_pairs_hook*.
Menambahkan dukungan untuk *object_pairs_hook*.
Supports the following objects and types by default:
To extend this to recognize other objects, subclass and implement a :meth:`~JSONEncoder.default` method with another method that returns a serializable object for ``o`` if possible, otherwise it should call the superclass implementation (to raise :exc:`TypeError`).
If *check_circular* 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 :exc:`RecursionError`). Otherwise, no such check takes place.
If *indent* 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 ``""`` will only insert newlines. ``None`` (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If *indent* is a string (such as ``"\t"``), that string is used to indent each level.
If specified, *default* 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 :exc:`TypeError`. If not specified, :exc:`TypeError` is raised.
Implement this method in a subclass such that it returns a serializable object for *o*, or calls the base implementation (to raise a :exc:`TypeError`).
Encode the given object, *o*, and yield each string representation as available. For example::
for chunk in json.JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)
Repeated names within an object are accepted, and only the value of the last name-value pair is used.
Other than the *ensure_ascii* parameter, this module is defined strictly in terms of conversion between Python objects and :class:`Unicode strings <str>`, and thus does not otherwise directly address the issue of character encodings.
Repeated Names Within an Object
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::
The *object_pairs_hook* parameter can be used to alter this behavior.
Top-level Non-Object, Non-Array Values
The old version of JSON specified by the obsolete :rfc:`4627` required that the top-level value of a JSON text must be either a JSON object or array (Python :class:`dict` or :class:`list`), and could not be a JSON null, boolean, number, or string value. :rfc:`7159` removed that restriction, and this module does not and has never implemented that restriction in either its serializer or its deserializer.
the maximum level of nesting of JSON objects and arrays
The :mod:`!json` module can be invoked as a script via ``python -m json`` to validate and pretty-print JSON objects. The :mod:`!json.tool` submodule implements this interface.
Parse every input line as separate JSON object.