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 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 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.

バヌゞョン 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 JSONDecoder subclass) -- If set, a custom JSON decoder. Additional keyword arguments to load() will be passed to the constructor of cls. If None (the default), JSONDecoder is 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 the dict. This feature can be used to implement custom decoders, for example JSON-RPC class hinting. Default None.

  • 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. Default None.

  • 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 to float(num_str). This can be used to parse JSON floats into custom datatypes, for example decimal.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 to int(num_str). This can be used to parse JSON integers into custom datatypes, for example float.

  • 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. Default None.

䟋倖:
  • 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 (a str, bytes or bytearray instance 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 TypeError will be raised when trying to encode keys that are not str, int, float, bool or None. 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¶

ヘルプメッセヌゞを出力したす

脚泚