Text of docs.python.org › id › 3 › library › json.html as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

json --- JSON encoder and decoder — Dokumentasi Python 3.15.2

Navigasi index modul | berikut | sebelum | Python » 3.15.2 documentation » The Python standard library » Penanganan Data Internet » json --- JSON encoder and decoder | Tema | json --- JSON encoder and decoder ¶ Source code: Lib/json/__init__.py JSON (JavaScript Object Notation) , specified by RFC 7159 (which obsoletes RFC 4627 ) and by ECMA-404 , is a lightweight data interchange format inspired by JavaScript object literal syntax (although it is not a strict subset of JavaScript [ 1 ] ).

Catatan 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. Peringatan 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.

This module exposes an API familiar to users of the standard library marshal and pickle modules. Hierarki penyandian objek Python dasar: >>> import json >>> json . dumps ([ 'foo' , { 'bar' : ( 'baz' , None , 1.0 , 2 )}]) '["foo", {"bar": ["baz", null, 1.0, 2]}]' >>> print ( json . dumps ( " \" foo \b ar" )) "\"foo\bar" >>> print ( json . dumps ( ' \u1234 ' )) "\u1234" >>> print ( json . dumps ( ' \\ ' )) "\\" >>> print ( json . dumps ({ "c" : 0 , "b" : 0 , "a" : 0 }, sort_keys = True )) {"a": 0, "b": 0, "c": 0} >>> from io import StringIO >>> io = StringIO () >>> json . dump ([ 'streaming API' ], io ) >>> io . getvalue () '["streaming API"]' Penyandian rapat: >>> import json >>> json . dumps ([ 1 , 2 , 3 , { '4' : 5 , '6' : 7 }], separators = ( ',' , ':' )) '[1,2,3,{"4":5,"6":7}]' Pencetakan indah: >>> import json >>> print ( json . dumps ({ '6' : 7 , '4' : 5 }, sort_keys = True , indent = 4 )) { "4": 5, "6": 7 } 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 + 2 j , default = custom_json ) '{"__complex__": true, "real": 1.0, "imag": 2.0}' Penerjemahan JSON: >>> import json >>> json . loads ( '["foo", {"bar":["baz", null, 1.0, 2]}]' ) ['foo', {'bar': ['baz', None, 1.0, 2]}] >>> json . loads ( '" \\ "foo \\ bar"' ) '"foo\x08ar' >>> from io import StringIO >>> io = StringIO ( '["streaming API"]' ) >>> json . load ( io ) ['streaming API'] 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)}) Memperluas JSONEncoder : >>> import json >>> 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 super () . default ( obj ) ... >>> json . dumps ( 2 + 1 j , cls = ComplexEncoder ) '[2.0, 1.0]' >>> ComplexEncoder () . encode ( 2 + 1 j ) '[2.0, 1.0]' >>> list ( ComplexEncoder () . iterencode ( 2 + 1 j )) ['[2.0', ', 1.0', ']'] Using json from the shell to validate and pretty-print: $ echo '{"json":"obj"}' | python -m json { "json": "obj" } $ echo '{1.2:3.4}' | python -m json Expecting property name enclosed in double quotes: line 1 column 2 (char 1) Lihat Command-line interface untuk dokumentasi terperinci.

Catatan JSON is a subset of YAML 1.2. The JSON produced by this module's default settings (in particular, the default separators value) is also a subset of YAML 1.0 and 1.1. This module can thus also be used as a YAML serializer. Catatan Encoders dan decoders dari modul ini secara bawaan mempertahankan urutan masukan dan keluaran. Urutan hanya akan hilang jika containers dasarnya tidak berurutan. Penggunaan Dasar ¶ 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 ) ¶ Serialize obj as a JSON formatted stream to fp (a .write() -supporting file-like object ) using this Python-to-JSON conversion table .

Catatan Unlike pickle and marshal , JSON is not a framed protocol, so trying to serialize multiple objects with repeated calls to dump() using the same fp will result in an invalid JSON file. Parameter : obj ( object ) -- The Python object to be serialized. fp ( file-like object ) -- The file-like object obj will be serialized to. The json module always produces str objects, not bytes objects, therefore fp.write() must support str input. skipkeys ( bool ) -- If True , keys that are not of a basic type ( str , int , float , bool , None ) will be skipped instead of raising a TypeError .

Default False . ensure_ascii ( bool ) -- If True (the default), the output is guaranteed to have all incoming non-ASCII and non-printable characters escaped. If False , all characters will be outputted as-is, except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters U+0000 through U+001F. check_circular ( bool ) -- If False , the circular reference check for container types is skipped and a circular reference will result in a RecursionError (or worse).

Default True . allow_nan ( bool ) -- If False , serialization of out-of-range float values ( nan , inf , -inf ) will result in a ValueError , in strict compliance with the JSON specification. If True (the default), their JavaScript equivalents ( NaN , Infinity , -Infinity ) are used. cls (a JSONEncoder subclass) -- If set, a custom JSON encoder with the default() method overridden, for serializing into custom datatypes.

If None (the default), JSONEncoder is used. indent ( int | str | None ) -- 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. separators ( tuple | None ) -- A two-tuple: (item_separator, key_separator) .

If None (the default), separators defaults to (', ', ': ') if indent is None , and (',', ': ') otherwise. For the most compact JSON, specify (',', ':') to eliminate whitespace. default ( callable | None) -- 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 TypeError . If None (the default), TypeError is raised. sort_keys ( bool ) -- If True , dictionaries will be outputted sorted by key.

Default False . Catatan Keys in key/value pairs of JSON are always of the type str . When a dictionary is converted into JSON, all the keys of the dictionary are converted 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, loads(dumps(x)) != x if x has non-string keys. sort_keys sorts the keys before they are converted to strings, so numeric keys are sorted by value, not by their string representation.

Berubah pada versi 3.2: Allow strings for indent in addition to integers. Berubah pada versi 3.4: Menggunakan (',', ': ') sebagai bawaan jika indent bukan None . Berubah pada versi 3.6: Semua paramet

The rest of this page is on the live site.