json — JSON encoder and decoder — Python 3.14.10 documentation
Navigation index modules | next | previous | Python » 3.14.10 documentation » The Python standard library » Internet Data Handling » json — JSON encoder and decoder | Theme | 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 ] ).
Note 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. Warning 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. Encoding basic Python object hierarchies: >>> 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"]' Compact encoding: >>> import json >>> json . dumps ([ 1 , 2 , 3 , { '4' : 5 , '6' : 7 }], separators = ( ',' , ':' )) '[1,2,3,{"4":5,"6":7}]' Pretty printing: >>> 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}' Decoding 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') Extending 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) See Command-line interface for detailed documentation.
Note 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. Note This module’s encoders and decoders preserve input and output order by default. Order is only lost if the underlying containers are unordered. Basic Usage ¶ 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 .
Note 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. Parameters : 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 . Note 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.
Changed in version 3.2: Allow strings for indent in addition to integers. Changed in version 3.4: Use (',', ': ') as default if indent is not None . Changed in version 3.6: All optional parameters are now keyword-only . 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 ) ¶ Serialize obj to a JSON formatted str using this conversion table .
The arguments have the same meaning a
The rest of this page is on the live site.