19.2. json JSON
JSON (JavaScript Object Notation) RFC 7159 (RFC 4627 obsolete) ECMA-404 JavaScript (JavaScript [1])
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')
>>> 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', ']']
$ 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)TypeErrorensure_ascii () true ASCII ensure_ascii false
check_circular false (
True)OverflowError()allow_nan (
True)float(nan,inf,-inf) JSONValueErrorallow_non JavaScript (NaN,Infinity,-Infinity)indent JSON 0
""None() indent indent ("\t")3.2 : indent
separators
(item_separator, key_separator)indentNone(', ', ': ')(',', ': ')JSON(',', ':')3.4 : indent
None(',', ': ')default JSON
TypeErrorTypeErrorsort_keys true (
False)JSONEncoder(default()) cls ;JSONEncoder
-
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) -
JSON
strJSON JSONloads(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_hookdict( JSON-RPC )object_pairs_hook object_pairs_hook
dict(collections.OrderedDict()) object_hook object_pairs_hook3.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'JSON3.1 : 'null', 'true', 'false' parse_constant
JSONDecodercls ;JSONDecoderJSON
JSONDecodeError
-
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) Pythonencoding
load()JSON
JSONDecodeError
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,-InfinityfloatJSONobject_hook JSON
dict( JSON-RPC )object_pairs_hook JSON object_pairs_hook
dict(collections.OrderedDict()) object_hook object_pairs_hook3.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'JSONstrict false (
True)'\t'()'\n''\r''\0'0-31JSON
JSONDecodeError-
decode(s) s (
strJSON ) PythonJSON
JSONDecodeError
-
raw_decode(s) s (
strJSON ) JSON Python s 2JSON
-
-
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
skipkeys false ()
str,int,float,NoneTypeErrorskipkeys trueensure_ascii () true ASCII ensure_ascii false
check_circular true () (
OverflowError)Trueallow_nan true ()
NaN,Infinity,-InfinityJSON JavaScriptTrueValueErrorsort_keys true (
False) JSONindent JSON 0
""None() indent indent ("\t")3.2 : indent
separators
(item_separator, key_separator)indentNone(', ', ': ')(',', ': ')JSON(',', ':')3.4 : indent
None(',', ': ')default JSON
TypeErrorTypeError-
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)
-
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.5.
JSON
- JSON
- JSON
- JSON
- JSON
Python Python
JSON JSON JSON IEEE 754 Python int decimal.Decimal ""
19.2.5.
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
| [1] | RFC 7159 JSON (ECMAScript Edition 5.1 ) JavaScript U+2028 (LINE SEPARATOR) U+2029 (PARAGRAPH SEPARATOR) |