"json" --- JSON encoder and decoder
***********************************

**소스 코드:** 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] ).

경고:

  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.

"json"은 표준 라이브러리 "marshal"과 "pickle" 모듈 사용자에게 익숙한
API를 제공합니다.

기본 파이썬 객체 계층 구조 인코딩:

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

Specializing 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 + 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', ']']

셸에서 "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 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.

참고:

  이 모듈의 인코더와 디코더는 기본적으로 입력과 출력 순서를 유지합니다
  . 하부 컨테이너에 순서가 없을 때만 순서가 손실됩니다.


기본 사용법
===========

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.

   참고:

     "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 characters
        escaped. If "False", these characters will be outputted as-is.

      * **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), the most compact representation is used.

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

   버전 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의 키/값 쌍에 있는 키는 항상 "str" 형입니다. 딕셔너리를 JSON
     으로 변환하면, 딕셔너리의 모든 키가 문자열로 강제 변환됩니다. 이
     것의 결과로, 딕셔너리를 JSON으로 변환한 다음 다시 딕셔너리로 변환
     하면, 딕셔너리가 원래의 것과 같지 않을 수 있습니다. 즉, x에 비 문
     자열 키가 있으면 "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* 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 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 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.

   * *parse_constant*는 더는 'null', 'true', 'false'에 대해 호출되지
     않습니다.

   버전 3.6에서 변경:

   * 모든 선택적 매개 변수는 이제 키워드-전용입니다.

   * *fp*는 이제 *바이너리 파일*이 될 수 있습니다. 입력 인코딩은
     UTF-8, UTF-16 또는 UTF-32 여야 합니다.

   버전 3.11에서 변경: The default *parse_int* of "int()" now limits
   the maximum length of the integer string via the interpreter's
   integer string conversion length limitation to help avoid denial of
   service attacks.

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            | 파이썬              |
   |=================|=====================|
   | 오브젝트        | dict                |
   | (object)        |                     |
   +-----------------+---------------------+
   | 배열(array)     | list                |
   +-----------------+---------------------+
   | 문자열(string)  | str                 |
   +-----------------+---------------------+
   | 숫자 (정수)     | int                 |
   +-----------------+---------------------+
   | 숫자 (실수)     | float               |
   +-----------------+---------------------+
   | 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*가 거짓이면 ("True"가 기본값입니다), 문자열 안에 제어 문자
   가 허용됩니다. 이 문맥에서 제어 문자는 0--31 범위의 문자 코드를 가
   진 것들인데, "'\t'" (탭), "'\n'", "'\r'" 및 "'\0'"을 포함합니다.

   역 직렬화되는 데이터가 유효한 JSON 문서가 아니면, "JSONDecodeError"
   가 발생합니다.

   버전 3.6에서 변경: 모든 매개 변수가 이제 키워드-전용입니다.

   decode(s)

      *s*(JSON 문서가 포함된 "str" 인스턴스)의 파이썬 표현을 반환합니
      다.

      주어진 JSON 문서가 유효하지 않으면 "JSONDecodeError"가 발생합니
      다.

   raw_decode(s)

      *s*(JSON 문서로 시작하는 "str")에서 JSON 문서를 디코딩하고, 파이
      썬 표현과 문서가 끝난 *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)

   파이썬 데이터 구조를 위한 확장 가능한 JSON 인코더

   기본적으로 다음 객체와 형을 지원합니다.:

   +------------------------------------------+-----------------+
   | 파이썬                                   | JSON            |
   |==========================================|=================|
   | dict                                     | 오브젝트        |
   |                                          | (object)        |
   +------------------------------------------+-----------------+
   | list, tuple                              | 배열(array)     |
   +------------------------------------------+-----------------+
   | str                                      | 문자열(string)  |
   +------------------------------------------+-----------------+
   | int, float, int와 float에서 파생된 열거  | 숫자(number)    |
   | 형                                       |                 |
   +------------------------------------------+-----------------+
   | True                                     | true            |
   +------------------------------------------+-----------------+
   | False                                    | false           |
   +------------------------------------------+-----------------+
   | None                                     | null            |
   +------------------------------------------+-----------------+

   버전 3.4에서 변경: int와 float 파생 Enum 클래스에 대한 지원이 추가
   되었습니다.

   To extend this to recognize other objects, subclass and implement a
   "default()" method with another method that returns a serializable
   object for "o" if possible, otherwise it should call the superclass
   implementation (to raise "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.

   *ensure_ascii*가 참(기본값)이면, 출력에서 모든 비 ASCII 문자가 이스
   케이프 되도록 보장됩니다. *ensure_ascii*가 거짓이면, 그 문자들은 있
   는 그대로 출력됩니다.

   If *check_circular* is true (the default), then lists, dicts, and
   custom encoded objects will be checked for circular references
   during encoding to prevent an infinite recursion (which would cause
   a "RecursionError"). Otherwise, no such check takes place.

   *allow_nan*이 참(기본값)이면, "NaN", "Infinity" 및 "-Infinity"는 그
   자체로 인코딩됩니다. 이 동작은 JSON 사양을 따르지 않지만, 대부분의
   JavaScript 기반 인코더 및 디코더와 일치합니다. 그렇지 않으면, 그러
   한 float를 인코딩하는 것은 "ValueError"가 됩니다.

   *sort_keys*가 참(기본값: "False")이면, 딕셔너리의 출력이 키로 정렬
   됩니다; JSON 직렬화를 이전과 비교할 수 있도록 해서 회귀 테스트에 유
   용합니다.

   *indent*가 음이 아닌 정수나 문자열이면, JSON 배열 요소와 오브젝트
   멤버가 해당 들여쓰기 수준으로 예쁘게 인쇄됩니다. 0, 음수 또는 """"
   의 들여쓰기 수준은 줄 넘김만 삽입합니다. "None"(기본값)은 가장 간결
   한(compact) 표현을 선택합니다. 양의 정수 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"를 발생시키기 위
      해서) 베이스 구현을 호출하도록 서브 클래스에 이 메서드를 구현하
      십시오.

      For example, to support arbitrary iterators, you could implement
      "default()" like this:

         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)

      파이썬 데이터 구조 *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입니다.

RFC에 의해 요구되는 것은 아니지만 허용되기 때문에, 이 모듈의 직렬화기
는 기본적으로 *ensure_ascii=True*를 설정하므로, 결과 문자열에 ASCII 문
자만 포함되도록 출력을 이스케이핑 합니다.

*ensure_ascii* 매개 변수 외에도, 이 모듈은 파이썬 객체와 "유니코드 문
자열" 사이의 변환으로 엄격하게 정의되어 있으므로, 문자 인코딩 문제를
직접 다루지 않습니다.

RFC는 JSON 텍스트의 시작 부분에 바이트 순서 표시(BOM)를 추가하는 것을
금지하고 있으며, 이 모듈의 직렬화기는 BOM을 출력에 추가하지 않습니다.
RFC는 JSON 역 직렬화기가 입력에서 초기 BOM을 무시하는 것을 허용하지만
요구하지는 않습니다. 이 모듈의 역 직렬화기는 초기 BOM이 있을 때
"ValueError"를 발생시킵니다.

RFC는 유효한 유니코드 문자에 해당하지 않는 바이트 시퀀스(예를 들어, 쌍
을 이루지 않은 UTF-16 대리 코드(unpaired UTF-16 surrogates))가 포함된
JSON 문자열을 명시적으로 금지하지 않지만, 상호 운용성 문제를 일으킬 수
있다고 지적하고 있습니다. 기본적으로, 이 모듈은 이러한 시퀀스의 코드
포인트를 받아들이고 (원래 "str"에 있을 때) 출력합니다.


무한대와 NaN 숫자 값
--------------------

RFC는 무한대나 NaN 숫자 값의 표현을 허용하지 않습니다. 그런데도, 기본
적으로, 이 모듈은 유효한 JSON 숫자 리터럴 값인 것처럼 "Infinity",
"-Infinity" 및 "NaN"을 받아들이고 출력합니다:

   >>> # 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 오브젝트나 배열(파이썬 "dict"나 "list")이어야 하고, JSON
null, 불리언, 숫자 또는 문자열 값이 될 수 없다고 요구합니다. **RFC
7159**는 그 제한을 제거했으며, 이 모듈은 직렬화기와 역 직렬화기에서 이
러한 제한을 구현하지 않으며, 그런 적도 없습니다.

이와 관계없이, 최대한의 상호 운용성을 위해, 여러분은 자발적으로 제한을
준수하기를 원할 수 있습니다.


구현 제약 사항
--------------

일부 JSON 역 직렬화기 구현은 다음과 같은 것들에 대한 제한을 설정할 수
있습니다:

* 받아들인 JSON 텍스트의 크기

* JSON 오브젝트와 배열의 최대 중첩 수준

* JSON 숫자의 범위와 정밀도

* JSON 문자열의 내용과 최대 길이

이 모듈은 관련 파이썬 데이터형 자체나 파이썬 인터프리터 자체의 한계 외
에는 어떤 제한도 가하지 않습니다.

JSON으로 직렬화할 때, 여러분의 JSON을 사용할 응용 프로그램에 있는 이러
한 제한 사항에 주의하십시오. 특히, JSON 숫자가 IEEE 754 배정도 숫자로
역 직렬화되는 것이 일반적이고, 그래서 그 표현의 범위와 정밀도 제한이
적용됩니다. 이것은 매우 큰 규모의 파이썬 "int" 값을 직렬화하거나,
"decimal.Decimal"과 같은 "색다른" 숫자 형의 인스턴스를 직렬화할 때 특
히 중요합니다.


명령 줄 인터페이스
==================

**소스 코드:** Lib/json/tool.py

======================================================================

"json.tool" 모듈은 JSON 객체의 유효성을 검사하고 예쁘게 인쇄하는 간단
한 명령 줄 인터페이스를 제공합니다.

If the optional "infile" and "outfile" arguments are not specified,
"sys.stdin" and "sys.stdout" will be used respectively:

   $ 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" 옵션을 사용하십시
오.


명령 줄 옵션
------------

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

   If *infile* is not specified, read from "sys.stdin".

outfile

   Write the output of the *infile* to the given *outfile*. Otherwise,
   write it to "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

   도움말 메시지를 표시합니다.

-[ 각주 ]-

[1] the errata for RFC 7159에서 언급했듯이, JSON은 문자열에
    U+2028(LINE SEPARATOR)과 U+2029(PARAGRAPH SEPARATOR) 문자를 허용하
    지만, JavaScript(ECMAScript Edition 5.1 기준)는 허용하지 않습니다.
