Text of docs.python.org › uk › 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 — Python 3.15.2 documentation

Навігація індекс модулі | наступний | попередній | Python » 3.15.2 documentation » The Python standard library » Обробка даних в Інтернеті » json — JSON encoder and decoder | Theme | json — JSON encoder and decoder ¶ Вихідний код: 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 ] ).

Примітка 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. Попередження 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. Кодування основних ієрархій об’єктів Python: >>> 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"]' Компактне кодування: >>> import json >>> json . dumps ([ 1 , 2 , 3 , { '4' : 5 , '6' : 7 }], separators = ( ',' , ':' )) '[1,2,3,{"4":5,"6":7}]' Гарний друк: >>> 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}' Декодування 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)}) Розширення 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) Перегляньте Command-line interface для детальної документації.

Примітка 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. Примітка Кодери та декодери цього модуля зберігають порядок введення та виведення за замовчуванням.

Порядок втрачається, лише якщо базові контейнери не впорядковані. Основне використання ¶ 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 .

Примітка На відміну від pickle і marshal , JSON не є фреймованим протоколом, тому спроба серіалізувати кілька об’єктів за допомогою повторних викликів dump() з використанням того самого fp призведе до недійсного JSON файл. Параметри : 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 . Примітка Keys in key/value pairs of JSON are always of the type str . When

The rest of this page is on the live site.