json --- JSON ãšã³ã³ãŒããŒãšãã³ãŒããŒÂ¶
ãœãŒã¹ã³ãŒã: Lib/json/__init__.py
JSON (JavaScript Object Notation) ã¯ã RFC 7159 (RFC 4627 ã obsolete) ãš ECMA-404 ã«ãã£ãŠå®çŸ©ããã軜éã®ããŒã¿äº€æçšã®ãã©ãŒãããã§ãã JavaScript ã®ãªããžã§ã¯ããªãã©ã«èšæ³ã«ç±æ¥ããŠããŸã (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.
èŠå
ä¿¡é ŒãããŠããªããœãŒã¹ããã® JSON ããŒã¿ãããŒã¹ãããšãã¯ååæ³šæããŠãã ãããæªæãæã£ã JSON æååã¯ãã³ãŒãã«èããéã® CPU ãšã¡ã¢ãªãªãœãŒã¹ãæ¶è²»ãããå¯èœæ§ããããŸããããŒã¹ããããŒã¿éãå¶éããããšãæšå¥šããŸãã
ãã®ã¢ãžã¥ãŒã«ã® 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({'6': 7, '4': 5}, sort_keys=True, indent=4))
{
"4": 5,
"6": 7
}
JSON ãªããžã§ã¯ãã®ãšã³ã³ãŒãã£ã³ã°æ¹æ³ãã«ã¹ã¿ãã€ãºãã:
>>> 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 + 2j, 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']
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 super().default(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', ']']
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)
詳现ã«ã€ããŠã¯ ã³ãã³ãã©ã€ã³ã»ã€ã³ã¿ãŒãã§ãŒã¹ ãåç §ããŠãã ããã
泚é
JSON 㯠YAML 1.2 ã®ãµãã»ããã§ãããã®ã¢ãžã¥ãŒã«ã®ããã©ã«ãèšå® (ç¹ã«ãããã©ã«ãã® ã»ãã¬ãŒã¿ å€) ã§çæããã JSON 㯠YAML 1.0 ããã³ 1.1 ã®ãµãã»ããã§ããããŸãããã®ã¢ãžã¥ãŒã«ã¯ YAML ã·ãªã¢ã©ã€ã¶ãšããŠã䜿ããŸãã
泚é
ãã®ã¢ãžã¥ãŒã«ã®ãšã³ã³ãŒããšãã³ãŒãã¯ãããã©ã«ãã§å ¥åé ãšåºåé ãä¿ã€ããã«ãªã£ãŠããŸããæ ¹åºã®ã³ã³ããã«é åºããªãå Žåã®ã¿ãé åºã倱ãããŸãã
åºæ¬çãªäœ¿ãæ¹Â¶
- 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)¶
ãã® PythonããJSONãžã®å€æè¡š ã䜿ã£ãŠã obj ã JSON 圢åŒã® fp (
.write()ããµããŒããããŠãã file-like object) ãžã®ã¹ããªãŒã ãšããŠçŽååããŸããæ³šé
pickleãmarshalãšã¯ç°ãªã JSON ã¯ãã¬ãŒã ä»ãã®ãããã³ã«ã§ã¯ãªãã®ã§ãåã fp ã«å¯Ÿãç¹°ãè¿ãdump()ãåŒã³ãè€æ°ã®ãªããžã§ã¯ããçŽååããããšãããšãäžæ£ãª JSON ãã¡ã€ã«ãäœãããŠããŸããŸãã- ãã©ã¡ãŒã¿:
obj (object) -- The Python object to be serialized.
fp (file-like object) -- The file-like object obj will be serialized to. The
jsonmodule always producesstrobjects, notbytesobjects, thereforefp.write()must supportstrinput.skipkeys (bool) -- If
True, keys that are not of a basic type (str,int,float,bool,None) will be skipped instead of raising aTypeError. DefaultFalse.ensure_ascii (bool) -- If
True(the default), the output is guaranteed to have all incoming non-ASCII and non-printable characters escaped. IfFalse, 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 aRecursionError(or worse). DefaultTrue.allow_nan (bool) -- If
False, serialization of out-of-rangefloatvalues (nan,inf,-inf) will result in aValueError, in strict compliance with the JSON specification. IfTrue(the default), their JavaScript equivalents (NaN,Infinity,-Infinity) are used.cls (a
JSONEncodersubclass) -- If set, a custom JSON encoder with thedefault()method overridden, for serializing into custom datatypes. IfNone(the default),JSONEncoderis 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. IfNone(the default), no newlines are inserted.separators (tuple | None) -- A two-tuple:
(item_separator, key_separator). IfNone(the default), separators defaults to(', ', ': ')if indent isNone, 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. IfNone(the default),TypeErroris raised.sort_keys (bool) -- If
True, dictionaries will be outputted sorted by key. DefaultFalse.
泚é
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)) != xif 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.ããŒãžã§ã³ 3.2 ã§å€æŽ: æŽæ°ã«å ããŠãæååã indent ã«äœ¿çšã§ããããã«ãªããŸããã
ããŒãžã§ã³ 3.4 ã§å€æŽ: indent ã
Noneã§ãªããã°(',', ': ')ãããã©ã«ãã§äœ¿ãããŸããããŒãžã§ã³ 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()ãšåãæå³ã§ãã
- json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)¶
Deserialize fp to a Python object using the JSON-to-Python conversion table.
- ãã©ã¡ãŒã¿:
fp (file-like object) -- A
.read()-supporting text file or binary file containing the JSON document to be deserialized.cls (a
JSONDecodersubclass) -- If set, a custom JSON decoder. Additional keyword arguments toload()will be passed to the constructor of cls. IfNone(the default),JSONDecoderis used.object_hook (callable | None) -- If set, a function that is called with the result of any JSON object literal decoded (a
dict). The return value of this function will be used instead of thedict. This feature can be used to implement custom decoders, for example JSON-RPC class hinting. DefaultNone.object_pairs_hook (callable | None) -- If set, a function that is called with the result of any JSON object literal decoded with an ordered list of pairs. The return value of this function will be used instead of the
dict. This feature can be used to implement custom decoders. If object_hook is also set, object_pairs_hook takes priority. DefaultNone.parse_float (callable | None) -- If set, a function that is called with the string of every JSON float to be decoded. If
None(the default), it is equivalent tofloat(num_str). This can be used to parse JSON floats into custom datatypes, for exampledecimal.Decimal.parse_int (callable | None) -- If set, a function that is called with the string of every JSON int to be decoded. If
None(the default), it is equivalent toint(num_str). This can be used to parse JSON integers into custom datatypes, for examplefloat.parse_constant (callable | None) -- If set, a function that is called with one of the following strings:
'-Infinity','Infinity', or'NaN'. This can be used to raise an exception if invalid JSON numbers are encountered. DefaultNone.
- äŸå€:
JSONDecodeError -- When the data being deserialized is not a valid JSON document.
UnicodeDecodeError -- When the data being deserialized does not contain UTF-8, UTF-16 or UTF-32 encoded data.
ããŒãžã§ã³ 3.1 ã§å€æŽ:
Added the optional object_pairs_hook parameter.
'null', 'true', 'false' ã«å¯Ÿã㊠parse_constant ã¯åŒã³ãããŸããã
ããŒãžã§ã³ 3.6 ã§å€æŽ:
ãã¹ãŠã®ãªãã·ã§ã³åŒæ°ã¯ã ããŒã¯ãŒãå°çš ã«ãªããŸããã
fp ã«ã¯ binary file åã䜿ããããã«ãªããŸãããå ¥åã®ãšã³ã³ãŒãã£ã³ã°ã¯ UTF-8, UTF-16, UTF-32 ã®ããããã§ãªããã°ãªããŸããã
ããŒãžã§ã³ 3.11 ã§å€æŽ: ããã©ã«ãã® parse_int ã§ãã
int()ã¯ãã€ã³ã¿ãŒããªã¿ã® integer string conversion length limitation ã«ããæŽæ°æååã®æå€§é·ãå¶éããããã«ãªãããµãŒãã¹ã劚害ããæ»æãæåŠããŸãã
- json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)¶
Identical to
load(), but instead of a file-like object, deserialize s (astr,bytesorbytearrayinstance containing a JSON document) to a Python object using this conversion table.ããŒãžã§ã³ 3.6 ã§å€æŽ: s ã«ã¯
bytesåãšbytearrayåã䜿ããããã«ãªããŸããã å ¥åãšã³ã³ãŒãã£ã³ã°ã¯ UTF-8, UTF-16, UTF-32 ã®ããããã§ãªããã°ãªããŸãããããŒãžã§ã³ 3.9 ã§å€æŽ: ããŒã¯ãŒãåŒæ° encoding ãåé€ãããŸããã
ãšã³ã³ãŒããšãã³ãŒã¶
- 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 is an optional function that will be called with the result of every JSON object decoded and its return value will be used in place of the given
dict. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting).object_pairs_hook is an optional function that will be called with the result of every JSON object decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the
dict. This feature can be used to implement custom decoders. If object_hook is also defined, the object_pairs_hook takes priority.ããŒãžã§ã³ 3.1 ã§å€æŽ: object_pairs_hook ã®ãµããŒãã远å ãããŸããã
parse_float is an optional function that will be called with the string of every JSON float to be decoded. By default, this is equivalent to
float(num_str). This can be used to use another datatype or parser for JSON floats (e.g.decimal.Decimal).parse_int is an optional function that will be called with the string of every JSON int to be decoded. By default, this is equivalent to
int(num_str). This can be used to use another datatype or parser for JSON integers (e.g.float).parse_constant is an optional function that will be called with one of the following strings:
'-Infinity','Infinity','NaN'. This can be used to raise an exception if invalid JSON numbers are encountered.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
intãfloat ãš int ã float ã®æŽŸçåæå
number
True
true
False
false
None
null
ããŒãžã§ã³ 3.4 ã§å€æŽ: int ãš float ã®æŽŸçåæåã¯ã©ã¹ã®å¯Ÿå¿ã远å ãããŸããã
ãã®ã¯ã©ã¹ãæ¡åŒµããŠä»ã®ãªããžã§ã¯ããèªèããããã«ããã«ã¯ããµãã¯ã©ã¹ãäœã£ãŠ
default()ã¡ãœãããæ¬¡ã®ããã«å®è£ ããŸããããäžã€å¥ã®ã¡ãœããã§ãªããžã§ã¯ãoã«å¯ŸããçŽååå¯èœãªãªããžã§ã¯ããè¿ããã®ãåŒã³åºãããã«ããŸãã倿ã§ããªãæã¯ã¹ãŒããŒã¯ã©ã¹ã®å®è£ ã (TypeErrorãéåºãããããã«) åŒã°ãªããã°ãªããŸãããIf skipkeys is false (the default), a
TypeErrorwill be raised when trying to encode keys that are notstr,int,float,boolorNone. If skipkeys is true, such items are simply skipped.If ensure_ascii is true (the default), the output is guaranteed to have all incoming non-ASCII and non-printable characters escaped. If ensure_ascii is false, all characters will be output 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 ã true (ããã©ã«ã) ãªãã°ããªã¹ããèŸæžããã³èªäœã§ãšã³ã³ãŒããããªããžã§ã¯ãã¯åŸªç°åç §ããªãããšã³ã³ãŒãäžã«ãã§ãã¯ãããç¡éååž° (ããã¯
RecursionErrorãåŒãèµ·ãããŸã) ã鲿¢ããŸãã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ãéåºããããã«) åŒã³åºããããŸããäŸãã°ãä»»æã®ã€ãã¬ãŒã¿ããµããŒãããå Žåã
default()ããã®ããã«å®è£ ã§ããŸã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 super().default(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)
äŸå€Â¶
- exception json.JSONDecodeError(msg, doc, pos)¶
ValueErrorã®ãµãã¯ã©ã¹ã§ã以äžã®è¿œå ã®å±æ§ãæã¡ãŸã:- msg¶
ãã©ãŒããããããŠããªããšã©ãŒã¡ãã»ãŒãžã§ãã
- doc¶
ããŒã¹å¯Ÿè±¡ JSON ããã¥ã¡ã³ãã§ãã
- pos¶
doc ã®ãè§£æã«å€±æããéå§ã€ã³ãã¯ã¹ã§ãã
- lineno¶
pos ã«å¯Ÿå¿ããè¡ã§ãã
- colno¶
pos ã«å¯Ÿå¿ããåã§ãã
Added in version 3.5.
æšæºãžã®æºæ ãšäºææ§Â¶
The JSON format is specified by RFC 7159 and by
ECMA-404.
This section details this module's level of compliance with the RFC.
For simplicity, JSONEncoder and JSONDecoder subclasses, and
parameters other than those explicitly mentioned, are not considered.
ãã®ã¢ãžã¥ãŒã«ã¯ãJavaScript ã§ã¯æ£ããã JSON ã§ã¯äžæ£ãªããã€ãã®æ¡åŒµãå®è£ ãããŠãããããå³å¯ãªæå³ã§ã¯ RFC ã«æºæ ããŠããŸãããç¹ã«:
ç¡éããã³ NaN ã®æ°å€ãåãä»ãããŸãåºåããŸã;
ãããªããžã§ã¯ãå ã§ã®åãååã®ç¹°ãè¿ããåãä»ããæåŸã®ååãšå€ã®ãã¢ã®å€ã®ã¿ã䜿çšããŸãã
ãã® RFC ã¯ãRFC æºæ ã®ããŒãµã RFC æºæ ã§ãªãå ¥åããã¹ããåãä»ããããšã蚱容ããŠããã®ã§ããã®ã¢ãžã¥ãŒã«ã®è±çŽååã¯æè¡çã«èšãã°ãããã©ã«ãã®èšå®ã§ã¯ RFC ã«æºæ ããŠããŸãã
æåãšã³ã³ãŒãã£ã³ã°Â¶
RFC ã¯ãUTF-8ãUTF-16ãUTF-32ã®ããããã§JSONã衚çŸããããã«èŠæ±ããŠãããUTF-8 ãæå€§ã®äºææ§ã確ä¿ããããã«æšå¥šãããããã©ã«ãã§ãã
As permitted, though not required, by the RFC, this module's serializer sets ensure_ascii=True by default, thus escaping the output so that the resulting strings only contain printable ASCII characters.
ensure_ascii ãã©ã¡ãŒã¿ä»¥å€ã¯ããã®ã¢ãžã¥ãŒã«ã¯ Python ãªããžã§ã¯ããš Unicode æåå ã®éã®å€æã«ãããŠå³å¯ã«å®çŸ©ãããŠããŠããã以å€ã®ãã©ã¡ãŒã¿ã§æåãšã³ã³ãŒãã£ã³ã°ã«çŽæ¥çã«é¢ãããã®ã¯ãããŸããã
RFC 㯠JSON ããã¹ãã®æåã«ãã€ããªãŒãããŒã¯(BOM)ã远å ããããšãçŠæ¢ããŠããŸãã®ã§ããã®ã¢ãžã¥ãŒã«ã¯ãã®åºåã« BOM ã远å ããŸãããRFC 㯠JSON ãã·ãªã¢ã©ã€ã¶ãå
¥åã®äžçªæåã® BOM ãç¡èŠããããšãã蚱容ã¯ããŸããæ±ããŠã¯ããŸããããã®ã¢ãžã¥ãŒã«ã®ãã·ãªã¢ã©ã€ã¶ã¯äžçªæåã® BOM ãèŠã€ãããš ValueError ãéåºããŸãã
RFC 㯠JSON æååã«æ£åœãª Unicode æåã«å¯Ÿå¿ä»ããªããã€ãå(äŸãã°ãã¢ã«ãªããªã UTF-16 ãµãã²ãŒãã®ãããã)ãå«ãŸããããšãæç€ºçã«çŠæ¢ããŠã¯ãããããã¡ããããã¯çžäºéçšæ§ã®åé¡ãåŒãèµ·ãããŸããããã©ã«ãã§ã¯ããã®ã¢ãžã¥ãŒã«ã¯(ãªãªãžãã«ã® str ã«ããå Žå)ãã®ãããªã·ãŒã±ã³ã¹ã®ã³ãŒããã€ã³ããåãåããåºåããŸãã
ç¡éããã³ NaN ã®æ°å€Â¶
RFC ã¯ãç¡éããã㯠NaN ã®æ°å€ã®è¡šçŸã¯èš±å¯ããŠããŸãããããã«ãé¢ãããããã©ã«ãã§ã¯ããã®ã¢ãžã¥ãŒã«ã¯ Infinityã-InfinityãNaN ãæ£ãã 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 ãã©ã¡ãŒã¿ã䜿ããŸãã
ãªããžã§ã¯ãäžã«éè€ããååã®æ±ã¶
RFC 㯠JSON ãªããžã§ã¯ãäžã®ååã¯ãŠããŒã¯ã§ãªããã°ãªããªããšèŠå®ããŠããŸãããJSONãªããžã§ã¯ãã§ååãç¹°ãè¿ãããå Žåã®æ±ãã«ã€ããŠæå®ããŠããŸãããããã©ã«ãã§ã¯ããã®ã¢ãžã¥ãŒã«ã¯äŸå€ãéåºããããããã«éè€ããååã®ãã¡ãæåŸã«åºçŸããååãšå€ã®ãã¢ä»¥å€ãç¡èŠããŸãã
>>> weird_json = '{"x": 1, "x": 2, "x": 3}'
>>> json.loads(weird_json)
{'x': 3}
object_pairs_hook ãã©ã¡ãŒã¿ã§ãã®åäœã倿Žã§ããŸãã
ãããã¬ãã«ã®éãªããžã§ã¯ããéé åã®å€ã®æ±ã¶
廿¢ããã RFC 4627 ã«ãã£ãŠèŠå®ãããå€ãããŒãžã§ã³ã® JSON ã§ã¯ãJSON ããã¹ãã®ãããã¬ãã«ã®å€ã¯ JSON ãªããžã§ã¯ããé
å(Python ã§ã® dict ã list)ã§ããããšãèŠæ±ããŠããŠãJSON ã® null, boolean, number, string ã§ããããšã¯èš±ãããŠããŸããã§ãããããã®å¶é㯠RFC 7159 ã«ããåãæãããŸããããã®ã¢ãžã¥ãŒã«ã¯ãã®å¶éãæã£ãŠããŸããããã·ãªã¢ã©ã€ã¶ã§ããã·ãªã¢ã©ã€ãºã§ããäžåºŠãšããŠãã®å¶éã§å®è£
ãããããšã¯ãããŸããã
ããã«ãé¢ããããçžäºéçšå¯èœæ§ãæå€§åããããªãã°ãããªãèªèº«ã®æã§èªçºçã«ãã®å¶çŽã«å¿ å®ã«åŸããããšæãã§ãããã
å®è£ ã®å¶é¶
ããã€ãã® JSON ãã·ãªã¢ã©ã€ã¶ã®å®è£ ã¯ã以äžã®å¶éãèšå®ããããšããããŸãã
åãå ¥ãããã JSON ããã¹ãã®ãµã€ãº
JSON ãªããžã§ã¯ããšé åã®ãã¹ãã®æå€§ã®æ·±ã
JSON æ°å€ã®ç¯å²ãšç²ŸåºŠ
JSON æååã®å å®¹ãšæå€§ã®é·ã
ãã®ã¢ãžã¥ãŒã«ã¯é¢é£ãã Python ããŒã¿åã Python ã€ã³ã¿ããªã¿èªèº«ã®å¶çŽã®äžçãè¶ ãããã®ãããªå¶çŽã匷èŠã¯ããŸããã
JSON ã«ã·ãªã¢ã©ã€ãºããéã«ã¯ãããªãã® JSON ãæ¶è²»ããåŽã®ã¢ããªã±ãŒã·ã§ã³ãæã€åœè©²å¶çŽã«æãã銳ããŠãã ããããšãããJSON æ°å€ã IEEE 754 å粟床浮åå°æ°ã«ãã·ãªã¢ã©ã€ãºããéã®åé¡ã¯ãããã¡ã§ãããªãã¡ãã®æå¹æ¡æ°ãšç²ŸåºŠã®å¶éã®åœ±é¿ãåããŸããããã¯ã極端ã«å€§ããªå€ãæã£ã Python int ãã·ãªã¢ã©ã€ãºãããšããããã㯠decimal.Decimal ã®ãã㪠"颚å€ãããª" æ°å€åãã·ãªã¢ã©ã€ãºãããšããã«ç¹ã«é¢ä¿ããããŸãã
ã³ãã³ãã©ã€ã³ã»ã€ã³ã¿ãŒãã§ãŒã¹Â¶
ãœãŒã¹ã³ãŒã: Lib/json/tool.py
The json module can be invoked as a script via python -m json
to validate and pretty-print JSON objects. The json.tool submodule
implements this interface.
ãªãã·ã§ã³åŒæ°ã® infile ãš outfile ãæå®ãããªãå Žåããããã sys.stdin ãš sys.stdout ã䜿çšãããŸãã
$ 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)
ããŒãžã§ã³ 3.5 ã§å€æŽ: åºåããå
¥åãšåãé åºã«ãªããŸãããèŸæžãããŒã§ã¢ã«ãã¡ãããé ã«äžŠã¹æ¿ããåºåãæ¬²ãããã°ã --sort-keys ãªãã·ã§ã³ã䜿ã£ãŠãã ããã
ããŒãžã§ã³ 3.14 ã§å€æŽ: The json module may now be directly executed as
python -m json. For backwards compatibility, invoking
the CLI as python -m json.tool remains supported.
ã³ãã³ãã©ã€ã³ãªãã·ã§ã³Â¶
- infile¶
æ€èšŒãè¡ãããããã¯æŽåœ¢åºåãè¡ã JSON ãã¡ã€ã«ãæå®ããŸã:
$ python -m json 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¶
èŸæžã®åºåããããŒã®ã¢ã«ãã¡ãããé ã«ãœãŒãããŸãã
Added in version 3.5.
- --no-ensure-ascii¶
é ASCII æåã®ãšã¹ã±ãŒããç¡å¹åããŸãããã詳ããã¯
json.dumps()ãåç §ããŠãã ãããAdded in version 3.9.
- --json-lines¶
ãã¹ãŠã®å ¥åè¡ãåå¥ã®JSON ãªããžã§ã¯ããšããŠããŒã¹ããŸãã
Added in version 3.8.
- --indent, --tab, --no-indent, --compact¶
ç©ºçœæåã®å¶åŸ¡ã®ããã®æä»çãªãªãã·ã§ã³ã
Added in version 3.9.
- -h, --help¶
ãã«ãã¡ãã»ãŒãžãåºåããŸã
èæ³š