19.2. json JSON

: Lib/json/__init__.py


JSON (JavaScript Object Notation) RFC 7159 (RFC 4627 obsolete) ECMA-404 JavaScript (JavaScript [1])

json API marshal pickle

Python :

>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print(json.dumps("\"foo\bar"))
"\"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({'4': 5, '6': 7}, sort_keys=True, indent=4))
{
    "4": 5,
    "6": 7
}

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']

JSON :

>>> 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')

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 json.JSONEncoder.default(self, obj)
...
>>> json.dumps(2 + 1j, cls=ComplexEncoder)
'[2.0, 1.0]'
>>> ComplexEncoder().encode(2 + 1j)
'[2.0, 1.0]'
>>> list(ComplexEncoder().iterencode(2 + 1j))
['[2.0', ', 1.0', ']']

json.tool :

$ echo '{"json":"obj"}' | python -m json.tool
{
    "json": "obj"
}
$ echo '{1.2:3.4}' | python -m json.tool
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

JSON YAML 1.2 ( ) JSON YAML 1.0 1.1 YAML

19.2.1.

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)

obj JSON fp (.write() file-like object)

skipkeys true ( False) (str, int, float, bool, None) TypeError

json bytes str fp.write() str

ensure_ascii () true ASCII ensure_ascii false

check_circular false ( True) OverflowError ()

allow_nan ( True) float (nan, inf, -inf) JSON ValueError allow_non JavaScript (NaN, Infinity, -Infinity)

indent JSON 0 "" None () indent indent ("\t" )

3.2 : indent

separators (item_separator, key_separator) indent None (', ', ': ') (',', ': ') JSON (',', ':')

3.4 : indent None (',', ': ')

default JSON TypeError TypeError

sort_keys true ( False )

JSONEncoder ( default() ) cls ; JSONEncoder

3.6 :

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)

obj JSON str dump()

pickle marshal JSON fp dump() JSON

JSON str JSON JSON loads(dumps(x)) != x

json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object using this conversion table.

object_hook (dict) object_hook dict ( JSON-RPC )

object_pairs_hook object_pairs_hook dict ( collections.OrderedDict() ) object_hook object_pairs_hook

3.1 : object_pairs_hook

parse_float JSON float(num_str) JSON ( decimal.Decimal)

parse_int JSON int(num_str) JSON ( float)

parse_constant : '-Infinity', 'Infinity', 'NaN', 'null', 'true', 'false' JSON

3.1 : 'null', 'true', 'false' parse_constant

JSONDecoder cls ; JSONDecoder

JSON JSONDecodeError

3.6 :

json.loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

s (JSON str, bytes, bytearray ) Python

encoding load()

JSON JSONDecodeError

3.6 : s bytes bytearray UTF-8, UTF-16, UTF-32

19.2.2.

class json.JSONDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)

JSON

:

JSON Python
object dict
array list
string str
number (int) int
number (real)
true True
false False
null None

NaN, Infinity, -Infinity float JSON

object_hook JSON dict ( JSON-RPC )

object_pairs_hook JSON object_pairs_hook dict ( collections.OrderedDict() ) object_hook object_pairs_hook

3.1 : object_pairs_hook

parse_float JSON float(num_str) JSON ( decimal.Decimal)

parse_int JSON int(num_str) JSON ( float)

parse_constant : '-Infinity', 'Infinity', 'NaN', 'null', 'true', 'false' JSON

strict false ( True) '\t' ()'\n''\r''\0' 0-31

JSON JSONDecodeError

3.6 :

decode(s)

s (str JSON ) Python

JSON JSONDecodeError

raw_decode(s)

s (str JSON ) JSON Python s 2

JSON

class json.JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

Python JSON

:

Python JSON
dict object
list, tuple array
str string
intfloat int float number
True true
False false
None null

3.4 : int float

default() o (TypeError )

skipkeys false () str, int, float, None TypeError skipkeys true

ensure_ascii () true ASCII ensure_ascii false

check_circular true () ( OverflowError ) True

allow_nan true () NaN, Infinity, -Infinity JSON JavaScript True ValueError

sort_keys true ( False) JSON

indent JSON 0 "" None () indent indent ("\t" )

3.2 : indent

separators (item_separator, key_separator) indent None (', ', ': ') (',', ': ') JSON (',', ':')

3.4 : indent None (',', ': ')

default JSON TypeError TypeError

3.6 :

default(o)

o (TypeError )

:

def default(self, o):
   try:
       iterable = iter(o)
   except TypeError:
       pass
   else:
       return list(iterable)
   # Let the base class default method raise the TypeError
   return json.JSONEncoder.default(self, o)
encode(o)

Python o JSON :

>>> json.JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
iterencode(o)

o yield :

for chunk in json.JSONEncoder().iterencode(bigobject):
    mysocket.write(chunk)

19.2.3.

exception json.JSONDecodeError(msg, doc, pos)

ValueError :

msg

doc

JSON

pos

doc

lineno

pos

colno

pos

3.5 .

19.2.4.

JSON RFC 7159 ECMA-404 RFC JSONEncoder JSONDecoder

JavaScript JSON RFC :

  • NaN ;

RFC RFC RFC RFC

19.2.4.1.

RFC UTF-8UTF-16UTF-32JSONUTF-8

RFC ensure_ascii=True ASCII

ensure_ascii Python Unicode

RFC JSON (BOM) BOM RFC JSON BOM BOM ValueError

RFC JSON Unicode ( UTF-16 )( str )

19.2.4.2. NaN

RFC NaN Infinity-InfinityNaN JSON :

>>> # Neither of these calls raises an exception, but the results are not valid JSON
>>> json.dumps(float('-inf'))
'-Infinity'
>>> json.dumps(float('nan'))
'NaN'
>>> # Same when deserializing
>>> json.loads('-Infinity')
-inf
>>> json.loads('NaN')
nan

allow_nan parse_constant

19.2.4.3.

RFC JSON JSON

>>> weird_json = '{"x": 1, "x": 2, "x": 3}'
>>> json.loads(weird_json)
{'x': 3}

object_pairs_hook

19.2.4.4.

RFC 4627 JSON JSON JSON (Python dict list)JSON null, boolean, number, string RFC 7159

19.2.4.5.

JSON

  • JSON
  • JSON
  • JSON
  • JSON

Python Python

JSON JSON JSON IEEE 754 Python int decimal.Decimal ""

19.2.5.

: Lib/json/tool.py


json.tool JSON

infile outfile sys.stdin sys.stdout :

$ echo '{"json": "obj"}' | python -m json.tool
{
    "json": "obj"
}
$ echo '{1.2:3.4}' | python -m json.tool
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

3.5 : --sort-keys

19.2.5.1.

infile

JSON :

$ python -m json.tool mp_films.json
[
    {
        "title": "And Now for Something Completely Different",
        "year": 1971
    },
    {
        "title": "Monty Python and the Holy Grail",
        "year": 1975
    }
]

infile sys.stdin

outfile

infile outfile sys.stdout

--sort-keys

3.5 .

-h, --help

[1]RFC 7159 JSON (ECMAScript Edition 5.1 ) JavaScript U+2028 (LINE SEPARATOR) U+2029 (PARAGRAPH SEPARATOR)