콘텐츠로 이동

!!! 경고 "🚧 작업 진행 중" 이 페이지는 진행 중인 작업입니다.

JSON

JSON 구문 분석

??? api "API 문서" pydantic.main.BaseModel.model_validate_json pydantic.type_adapter.TypeAdapter.validate_json pydantic_core.from_json

Pydantic은 다음을 달성하는 데 도움이 되는 내장 JSON 구문 분석을 제공합니다.

  • 타사 라이브러리를 사용하지 않고도 성능이 크게 향상됩니다.
  • 사용자 정의 오류 지원
  • strict 사양 지원

다음은 model_validate_json 메소드를 통한 Pydantic의 내장 JSON 구문 분석의 예입니다. 모델의 유형 주석과 일치하지 않는 JSON 데이터를 구문 분석하는 동안 strict 사양에 대한 지원을 보여줍니다.

from datetime import date
from typing import Tuple

from pydantic import BaseModel, ConfigDict, ValidationError


class Event(BaseModel):
    model_config = ConfigDict(strict=True)

    when: date
    where: Tuple[int, int]


json_data = '{"when": "1987-01-28", "where": [51, -1]}'
print(Event.model_validate_json(json_data))  # (1)!
#> when=datetime.date(1987, 1, 28) where=(51, -1)

try:
    Event.model_validate({'when': '1987-01-28', 'where': [51, -1]})  # (2)!
except ValidationError as e:
    print(e)
    """
    2 validation errors for Event
    when
      Input should be a valid date [type=date_type, input_value='1987-01-28', input_type=str]
    where
      Input should be a valid tuple [type=tuple_type, input_value=[51, -1], input_type=list]
    """
  1. JSON에는 date 또는 튜플 유형이 없지만 Pydantic은 JSON을 직접 구문 분석할 때 각각 문자열과 배열을 입력으로 허용한다는 것을 알고 있습니다.
  2. 동일한 값을 model_validate 메소드에 전달하면 Pydantic은 strict 구성이 활성화되어 있기 때문에 유효성 검사 오류를 발생시킵니다.

v2.5.0 이상에서 Pydantic은 빠르고 반복 가능한 JSON 파서인 jiter 사용하여 JSON 데이터를 구문 분석합니다. serde 와 비교하여 jiter 사용하면 성능이 어느 정도 향상되며 향후에는 훨씬 더 좋아질 것입니다.

jiter JSON 구문 분석기는 serde JSON 구문 분석기와 거의 완전히 호환되며, 한 가지 눈에 띄는 개선 사항은 jiter infNaN 값의 역직렬화를 지원한다는 것입니다. 앞으로 jiter 유효하지 않은 값이 포함된 원래 JSON 입력의 위치를 포함하도록 지원 유효성 검사 오류를 활성화할 예정입니다.

부분 JSON 구문 분석

v2.7.0부터 Pydantic의 JSON 파서는 pydantic_core.from_json을 통해 노출되는 부분 JSON 구문 분석을 지원합니다. 다음은 이 기능이 실제로 사용되는 예입니다.

from pydantic_core import from_json

partial_json_data = '["aa", "bb", "c'  # (1)!

try:
    result = from_json(partial_json_data, allow_partial=False)
except ValueError as e:
    print(e)  # (2)!
    #> EOF while parsing a string at line 1 column 15

result = from_json(partial_json_data, allow_partial=True)
print(result)  # (3)!
#> ['aa', 'bb']
  1. JSON 목록이 불완전합니다. 닫는 문자가 없습니다. "]
  2. allow_partial False (기본값)로 설정하면 구문 분석 오류가 발생합니다.
  3. allow_partialTrue 로 설정되면 입력의 일부가 성공적으로 역직렬화됩니다.

이는 부분 사전을 역직렬화하는 데에도 작동합니다. 예를 들어:

from pydantic_core import from_json

partial_dog_json = '{"breed": "lab", "name": "fluffy", "friends": ["buddy", "spot", "rufus"], "age'
dog_dict = from_json(partial_dog_json, allow_partial=True)
print(dog_dict)
#> {'breed': 'lab', 'name': 'fluffy', 'friends': ['buddy', 'spot', 'rufus']}

!!! Tip " LLM 출력 유효성 검사" 이 기능은 LLM 출력 유효성을 검사하는 데 특히 유용합니다. 우리는 이 주제에 관해 몇 가지 블로그 게시물을 작성했으며 여기에서 찾을 수 있습니다.

Pydantic의 향후 버전에서는 Pydantic의 다른 JSON 검증 기능(pydantic.main.BaseModel.model_validate_jsonpydantic.type_adapter.TypeAdapter.validate_json) 또는 모델 구성. 계속 지켜봐주세요 🚀!

지금은 pydantic_core.from_json와 함께 사용할 수 있습니다. pydantic.main.BaseModel.model_validate를 사용하면 동일한 결과를 얻을 수 있습니다. 예는 다음과 같습니다.

from pydantic_core import from_json

from pydantic import BaseModel


class Dog(BaseModel):
    breed: str
    name: str
    friends: list


partial_dog_json = '{"breed": "lab", "name": "fluffy", "friends": ["buddy", "spot", "rufus"], "age'
dog = Dog.model_validate(from_json(partial_dog_json, allow_partial=True))
print(repr(dog))
#> Dog(breed='lab', name='fluffy', friends=['buddy', 'spot', 'rufus'])

!!! 팁 부분 JSON 구문 분석이 안정적으로 작동하려면 모델의 모든 필드에 기본값이 있어야 합니다.

부분 JSON 구문 분석에서 기본값을 사용하는 방법에 대한 자세한 내용은 다음 예를 확인하세요.

부분 JSON 구문 분석에 기본값 사용

from typing import Any, Optional, Tuple

import pydantic_core
from typing_extensions import Annotated

from pydantic import BaseModel, ValidationError, WrapValidator


def default_on_error(v, handler) -> Any:
    """
    Raise a PydanticUseDefault exception if the value is missing.

    This is useful for avoiding errors from partial
    JSON preventing successful validation.
    """
    try:
        return handler(v)
    except ValidationError as exc:
        # there might be other types of errors resulting from partial JSON parsing
        # that you allow here, feel free to customize as needed
        if all(e['type'] == 'missing' for e in exc.errors()):
            raise pydantic_core.PydanticUseDefault()
        else:
            raise


class NestedModel(BaseModel):
    x: int
    y: str


class MyModel(BaseModel):
    foo: Optional[str] = None
    bar: Annotated[
        Optional[Tuple[str, int]], WrapValidator(default_on_error)
    ] = None
    nested: Annotated[
        Optional[NestedModel], WrapValidator(default_on_error)
    ] = None


m = MyModel.model_validate(
    pydantic_core.from_json('{"foo": "x", "bar": ["world",', allow_partial=True)
)
print(repr(m))
#> MyModel(foo='x', bar=None, nested=None)


m = MyModel.model_validate(
    pydantic_core.from_json(
        '{"foo": "x", "bar": ["world", 1], "nested": {"x":', allow_partial=True
    )
)
print(repr(m))
#> MyModel(foo='x', bar=('world', 1), nested=None)

캐싱 문자열

v2.7.0부터 Pydantic의 JSON 파서는 JSON 구문 분석 및 유효성 검사 중에 Python 문자열이 캐시되는 방식을 구성하는 지원을 제공합니다(Python 유효성 검사 중에 Python 문자열이 Rust 문자열에서 구성되는 경우, 예: strip_whitespace=True 이후). cache_strings 설정은 model configpydantic_core.from_json을 통해 노출됩니다.

cache_strings 설정은 다음 값 중 하나를 사용할 수 있습니다.

  • True 또는 'all' (기본값): 모든 문자열을 캐시합니다.
  • 'keys' : 사전 키만 캐시합니다. 이는 pydantic_core.from_json과 함께 사용하거나 Json을 사용하여 JSON을 구문 분석할 때만 적용됩니다.
  • False 또는 'none' : 캐싱 없음

문자열 캐싱 기능을 사용하면 성능이 향상되지만 메모리 사용량이 약간 늘어납니다.

!!! "문자열 캐싱 세부 정보"를 참고하세요.

1. Strings are cached using a fully associative cache with a size of
[16,384](https://github.com/pydantic/jiter/blob/5bbdcfd22882b7b286416b22f74abd549c7b2fd7/src/py_string_cache.rs#L113).
2. Only strings where `len(string) < 64` are cached.
3. There is some overhead to looking up the cache, which is normally worth it to avoid constructing strings.
However, if you know there will be very few repeated strings in your data, you might get a performance boost by disabling this setting with `cache_strings=False`.

JSON 직렬화

??? api "API 문서" pydantic.main.BaseModel.model_dump_json
pydantic.type_adapter.TypeAdapter.dump_json
pydantic_core.to_json

JSON 직렬화에 대한 자세한 내용은 직렬화 개념 페이지를 참조하세요.


本文总阅读量