コンテンツにスキップ

JSON Schema

Usage Documentation

Json Schema

json_schemaモジュールには、JSON Schemaの生成方法をカスタマイズできるようにするクラスと関数が含まれています。

一般的に、このモジュールを直接使用する必要はありません。代わりに、BaseModel.model_json_schemaTypeAdapter.json_schemaを使用できます。

CoreSchemaOrFieldType module-attribute

CoreSchemaOrFieldType = Literal[
    CoreSchemaType, CoreSchemaFieldType
]

core_schema.CoreSchemaTypecore_schema.CoreSchemaFieldTypeの和集合を表す、定義済みスキーマ型の型エイリアスです。

JsonSchemaValue module-attribute

JsonSchemaValue = Dict[str, Any]

JSONスキーマ値の型の別名。任意のJSON値に対する文字列キーのディクショナリです。

JsonSchemaMode module-attribute

JsonSchemaMode = Literal['validation', 'serialization']

JSONスキーマのモードを表す型エイリアス。"検証"または"シリアライゼーション"のいずれか。

タイプによっては、検証への入力がシリアライゼーションの出力と異なる場合があります。 たとえば、計算フィールドはシリアライズ時にのみ存在し、検証時には提供されません。 このフラグは、検証入力に必要なJSONスキーマを必要とするか、直列化出力によって一致させるかを示す方法を提供します。

JsonSchemaWarningKind module-attribute

JsonSchemaWarningKind = Literal[
    "skipped-choice", "non-serializable-default"
]

JSONスキーマ生成時に発生する可能性のある警告の種類を表す型エイリアス。

詳細については、GenerateJsonSchema.render_warning_messageを参照してください。

DEFAULT_REF_TEMPLATE module-attribute

DEFAULT_REF_TEMPLATE = '#/$defs/{model}'

参照名の生成に使用されるデフォルトのフォーマット文字列。

PydanticJsonSchemaWarning

Bases: UserWarning

このクラスは、JSONスキーマの生成中に生成される警告を発行するために使用されます。 詳細については、GenerateJsonSchema.emit_warningおよびGenerateJsonSchema.render_warning_messageメソッドを参照してください。これらのメソッドは、警告の動作を制御するためにオーバーライドできます。

GenerateJsonSchema

GenerateJsonSchema(
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
)

JSONスキーマを生成するためのクラス。

このクラスは、設定されたパラメータに基づいてJSONスキーマを生成します。デフォルトのスキーマダイアレクトはhttps://json-schema.org/draft/2020-12/schemaです。 このクラスは、複数の名前を持つフィールドの処理方法を設定するためにby_aliasを使用し、参照名をフォーマットするためにref_templateを使用します。

Attributes:

Name Type Description
schema_dialect

スキーマの生成に使用されるJSONスキーマダイアレクト。ダイアレクトの詳細については、JSONスキーマのドキュメントのDeclaring a Dialectを参照してください。

ignored_warning_kind

スキーマの生成時に無視される警告。self.render_warning_messageは、引数kindignored_warning_kindにある場合は何もしません。この値は、どの警告が出されるかを簡単に制御するためにサブクラスで変更できます。

by_alias

スキーマの生成時にフィールドの別名を使用するかどうか。

ref_template

参照名を生成するときに使用されるフォーマット文字列。

core_to_json_refs dict[CoreModeRef, JsonRef]

コア参照からJSON参照へのマッピングです。

core_to_defs_refs dict[CoreModeRef, DefsRef]

コア参照から定義参照へのマッピング。

defs_to_core_refs dict[DefsRef, CoreModeRef]

定義参照からコア参照へのマッピング。

json_to_defs_refs dict[JsonRef, DefsRef]

JSON参照から定義参照へのマッピングです。

definitions dict[DefsRef, JsonSchemaValue]

スキーマ内の定義。

Parameters:

Name Type Description Default
by_alias bool

生成されたスキーマでフィールドの別名を使用するかどうか。

True
ref_template str

参照名を生成するときに使用するフォーマット文字列。

DEFAULT_REF_TEMPLATE

Raises:

Type Description
JsonSchemaError

スキーマの生成後にクラスのインスタンスが誤って再利用された場合。

Source code in pydantic/json_schema.py
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
def __init__(self, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE):
    self.by_alias = by_alias
    self.ref_template = ref_template

    self.core_to_json_refs: dict[CoreModeRef, JsonRef] = {}
    self.core_to_defs_refs: dict[CoreModeRef, DefsRef] = {}
    self.defs_to_core_refs: dict[DefsRef, CoreModeRef] = {}
    self.json_to_defs_refs: dict[JsonRef, DefsRef] = {}

    self.definitions: dict[DefsRef, JsonSchemaValue] = {}
    self._config_wrapper_stack = _config.ConfigWrapperStack(_config.ConfigWrapper({}))

    self._mode: JsonSchemaMode = 'validation'

    # The following includes a mapping of a fully-unique defs ref choice to a list of preferred
    # alternatives, which are generally simpler, such as only including the class name.
    # At the end of schema generation, we use these to produce a JSON schema with more human-readable
    # definitions, which would also work better in a generated OpenAPI client, etc.
    self._prioritized_defsref_choices: dict[DefsRef, list[DefsRef]] = {}
    self._collision_counter: dict[str, int] = defaultdict(int)
    self._collision_index: dict[str, int] = {}

    self._schema_type_to_method = self.build_schema_type_to_method()

    # When we encounter definitions we need to try to build them immediately
    # so that they are available schemas that reference them
    # But it's possible that CoreSchema was never going to be used
    # (e.g. because the CoreSchema that references short circuits is JSON schema generation without needing
    #  the reference) so instead of failing altogether if we can't build a definition we
    # store the error raised and re-throw it if we end up needing that def
    self._core_defs_invalid_for_json_schema: dict[DefsRef, PydanticInvalidForJsonSchema] = {}

    # This changes to True after generating a schema, to prevent issues caused by accidental re-use
    # of a single instance of a schema generator
    self._used = False

ValidationsMapping

このクラスには、core_schema属性名から対応するJSONスキーマ属性名へのマッピングだけが含まれています。 必要になる可能性は低いと思いますが、原則として、GenerateJsonSchemaのサブクラスでこのクラスをオーバーライドして(GenerateJsonSchema.Validation Mappingから継承することによって)、これらのマッピングを変更することができます。

build_schema_type_to_method

build_schema_type_to_method() -> dict[
    CoreSchemaOrFieldType,
    Callable[[CoreSchemaOrField], JsonSchemaValue],
]

JSONスキーマを生成するメソッドにフィールドをマッピングする辞書を構築します。

Returns:

Type Description
dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]]

ハンドラメソッドへのCoreSchemaOrFieldTypeのマッピングを含むディクショナリです。

Raises:

Type Description
TypeError

指定されたpydanticコアスキーマタイプのJSONスキーマを生成するためのメソッドが定義されていない場合。

Source code in pydantic/json_schema.py
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def build_schema_type_to_method(
    self,
) -> dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]]:
    """JSONスキーマを生成するメソッドにフィールドをマッピングする辞書を構築します。

    Returns:
        ハンドラメソッドへの`CoreSchemaOrFieldType`のマッピングを含むディクショナリです。

    Raises:
        TypeError: 指定されたpydanticコアスキーマタイプのJSONスキーマを生成するためのメソッドが定義されていない場合。
    """
    mapping: dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]] = {}
    core_schema_types: list[CoreSchemaOrFieldType] = _typing_extra.all_literal_values(
        CoreSchemaOrFieldType  # type: ignore
    )
    for key in core_schema_types:
        method_name = f"{key.replace('-', '_')}_schema"
        try:
            mapping[key] = getattr(self, method_name)
        except AttributeError as e:  # pragma: no cover
            raise TypeError(
                f'No method for generating JsonSchema for core_schema.type={key!r} '
                f'(expected: {type(self).__name__}.{method_name})'
            ) from e
    return mapping

generate_definitions

generate_definitions(
    inputs: Sequence[
        tuple[JsonSchemaKeyT, JsonSchemaMode, CoreSchema]
    ]
) -> tuple[
    dict[
        tuple[JsonSchemaKeyT, JsonSchemaMode],
        JsonSchemaValue,
    ],
    dict[DefsRef, JsonSchemaValue],
]

コアスキーマのリストからJSONスキーマ定義を生成し、生成された定義を、入力キーを定義参照にリンクするマッピングと組み合わせます。

Parameters:

Name Type Description Default
inputs Sequence[tuple[JsonSchemaKeyT, JsonSchemaMode, CoreSchema]]

タプルのシーケンス。

  • 最初の要素はJSONスキーマのキー型です。
  • 2番目の要素はJSONモードで、"検証"または"シリアライゼーション"のいずれかです。
  • 3番目の要素はコア・スキーマです。
required

Returns:

Name Type Description
次の条件を満たすタプル tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], dict[DefsRef, JsonSchemaValue]]
  • 最初の要素は、JSONスキーマ・キー・タイプとJSONモードのタプルをキーとし、その入力ペアに対応するJSONスキーマを値とする辞書です(これらのスキーマは、2番目に返された要素で定義されている定義へのJsonRef参照を持つ場合があります)。
  • 2番目の要素は、最初に返された要素からのJSONスキーマの定義参照をキーとし、実際のJSONスキーマ定義を値とする辞書です。

Raises:

Type Description
PydantictUserError

JSONスキーマジェネレータがすでにJSONスキーマの生成に使用されている場合に発生します。

Source code in pydantic/json_schema.py
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
def generate_definitions(
    self, inputs: Sequence[tuple[JsonSchemaKeyT, JsonSchemaMode, core_schema.CoreSchema]]
) -> tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], dict[DefsRef, JsonSchemaValue]]:
    """コアスキーマのリストからJSONスキーマ定義を生成し、生成された定義を、入力キーを定義参照にリンクするマッピングと組み合わせます。

    Args:
        inputs:タプルのシーケンス。

            - 最初の要素はJSONスキーマのキー型です。
            - 2番目の要素はJSONモードで、"検証"または"シリアライゼーション"のいずれかです。
            - 3番目の要素はコア・スキーマです。

    Returns:
        次の条件を満たすタプル:

            - 最初の要素は、JSONスキーマ・キー・タイプとJSONモードのタプルをキーとし、その入力ペアに対応するJSONスキーマを値とする辞書です(これらのスキーマは、2番目に返された要素で定義されている定義へのJsonRef参照を持つ場合があります)。
            - 2番目の要素は、最初に返された要素からのJSONスキーマの定義参照をキーとし、実際のJSONスキーマ定義を値とする辞書です。

    Raises:
        PydantictUserError: JSONスキーマジェネレータがすでにJSONスキーマの生成に使用されている場合に発生します。
    """
    if self._used:
        raise PydanticUserError(
            'This JSON schema generator has already been used to generate a JSON schema. '
            f'You must create a new instance of {type(self).__name__} to generate a new JSON schema.',
            code='json-schema-already-used',
        )

    for key, mode, schema in inputs:
        self._mode = mode
        self.generate_inner(schema)

    definitions_remapping = self._build_definitions_remapping()

    json_schemas_map: dict[tuple[JsonSchemaKeyT, JsonSchemaMode], DefsRef] = {}
    for key, mode, schema in inputs:
        self._mode = mode
        json_schema = self.generate_inner(schema)
        json_schemas_map[(key, mode)] = definitions_remapping.remap_json_schema(json_schema)

    json_schema = {'$defs': self.definitions}
    json_schema = definitions_remapping.remap_json_schema(json_schema)
    self._used = True
    return json_schemas_map, _sort_json_schema(json_schema['$defs'])  # type: ignore

generate

generate(
    schema: CoreSchema, mode: JsonSchemaMode = "validation"
) -> JsonSchemaValue

指定されたスキーマのJSONスキーマを指定されたモードで生成します。

Parameters:

Name Type Description Default
schema CoreSchema

Pydanticモデル。

required
mode JsonSchemaMode

スキーマを生成するモード。デフォルトは"検証"です。

'validation'

Returns:

Type Description
JsonSchemaValue

指定されたスキーマを表すJSONスキーマ。

Raises:

Type Description
PydantictUserError

JSONスキーマジェネレータがすでにJSONスキーマの生成に使用されている場合。

Source code in pydantic/json_schema.py
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
def generate(self, schema: CoreSchema, mode: JsonSchemaMode = 'validation') -> JsonSchemaValue:
    """指定されたスキーマのJSONスキーマを指定されたモードで生成します。

    Args:
        schema: Pydanticモデル。
        mode: スキーマを生成するモード。デフォルトは"検証"です。

    Returns:
        指定されたスキーマを表すJSONスキーマ。

    Raises:
        PydantictUserError: JSONスキーマジェネレータがすでにJSONスキーマの生成に使用されている場合。
    """
    self._mode = mode
    if self._used:
        raise PydanticUserError(
            'This JSON schema generator has already been used to generate a JSON schema. '
            f'You must create a new instance of {type(self).__name__} to generate a new JSON schema.',
            code='json-schema-already-used',
        )

    json_schema: JsonSchemaValue = self.generate_inner(schema)
    json_ref_counts = self.get_json_ref_counts(json_schema)

    # Remove the top-level $ref if present; note that the _generate method already ensures there are no sibling keys
    ref = cast(JsonRef, json_schema.get('$ref'))
    while ref is not None:  # may need to unpack multiple levels
        ref_json_schema = self.get_schema_from_definitions(ref)
        if json_ref_counts[ref] > 1 or ref_json_schema is None:
            # Keep the ref, but use an allOf to remove the top level $ref
            json_schema = {'allOf': [{'$ref': ref}]}
        else:
            # "Unpack" the ref since this is the only reference
            json_schema = ref_json_schema.copy()  # copy to prevent recursive dict reference
            json_ref_counts[ref] -= 1
        ref = cast(JsonRef, json_schema.get('$ref'))

    self._garbage_collect_definitions(json_schema)
    definitions_remapping = self._build_definitions_remapping()

    if self.definitions:
        json_schema['$defs'] = self.definitions

    json_schema = definitions_remapping.remap_json_schema(json_schema)

    # For now, we will not set the $schema key. However, if desired, this can be easily added by overriding
    # this method and adding the following line after a call to super().generate(schema):
    # json_schema['$schema'] = self.schema_dialect

    self._used = True
    return _sort_json_schema(json_schema)

generate_inner

generate_inner(
    schema: CoreSchemaOrField,
) -> JsonSchemaValue

指定されたコアスキーマのJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema CoreSchemaOrField

指定されたコアスキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
def generate_inner(self, schema: CoreSchemaOrField) -> JsonSchemaValue:  # noqa: C901
    """指定されたコアスキーマのJSONスキーマを生成します。

    Args:
        schema: 指定されたコアスキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    # If a schema with the same CoreRef has been handled, just return a reference to it
    # Note that this assumes that it will _never_ be the case that the same CoreRef is used
    # on types that should have different JSON schemas
    if 'ref' in schema:
        core_ref = CoreRef(schema['ref'])  # type: ignore[typeddict-item]
        core_mode_ref = (core_ref, self.mode)
        if core_mode_ref in self.core_to_defs_refs and self.core_to_defs_refs[core_mode_ref] in self.definitions:
            return {'$ref': self.core_to_json_refs[core_mode_ref]}

    # Generate the JSON schema, accounting for the json_schema_override and core_schema_override
    metadata_handler = _core_metadata.CoreMetadataHandler(schema)

    def populate_defs(core_schema: CoreSchema, json_schema: JsonSchemaValue) -> JsonSchemaValue:
        if 'ref' in core_schema:
            core_ref = CoreRef(core_schema['ref'])  # type: ignore[typeddict-item]
            defs_ref, ref_json_schema = self.get_cache_defs_ref_schema(core_ref)
            json_ref = JsonRef(ref_json_schema['$ref'])
            self.json_to_defs_refs[json_ref] = defs_ref
            # Replace the schema if it's not a reference to itself
            # What we want to avoid is having the def be just a ref to itself
            # which is what would happen if we blindly assigned any
            if json_schema.get('$ref', None) != json_ref:
                self.definitions[defs_ref] = json_schema
                self._core_defs_invalid_for_json_schema.pop(defs_ref, None)
            json_schema = ref_json_schema
        return json_schema

    def convert_to_all_of(json_schema: JsonSchemaValue) -> JsonSchemaValue:
        if '$ref' in json_schema and len(json_schema.keys()) > 1:
            # technically you can't have any other keys next to a "$ref"
            # but it's an easy mistake to make and not hard to correct automatically here
            json_schema = json_schema.copy()
            ref = json_schema.pop('$ref')
            json_schema = {'allOf': [{'$ref': ref}], **json_schema}
        return json_schema

    def handler_func(schema_or_field: CoreSchemaOrField) -> JsonSchemaValue:
        """入力スキーマに基づいてJSONスキーマを生成します。

        Args:
            schema_or_field: JSONスキーマを生成するためのコア・スキーマです。

        Returns:
            生成されたJSONスキーマ。

        Raises:
            TypeError: 予期しないスキーマ・タイプが検出された場合。
        """
        # Generate the core-schema-type-specific bits of the schema generation:
        json_schema: JsonSchemaValue | None = None
        if self.mode == 'serialization' and 'serialization' in schema_or_field:
            ser_schema = schema_or_field['serialization']  # type: ignore
            json_schema = self.ser_schema(ser_schema)
        if json_schema is None:
            if _core_utils.is_core_schema(schema_or_field) or _core_utils.is_core_schema_field(schema_or_field):
                generate_for_schema_type = self._schema_type_to_method[schema_or_field['type']]
                json_schema = generate_for_schema_type(schema_or_field)
            else:
                raise TypeError(f'Unexpected schema type: schema={schema_or_field}')
        if _core_utils.is_core_schema(schema_or_field):
            json_schema = populate_defs(schema_or_field, json_schema)
            json_schema = convert_to_all_of(json_schema)
        return json_schema

    current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, handler_func)

    for js_modify_function in metadata_handler.metadata.get('pydantic_js_functions', ()):

        def new_handler_func(
            schema_or_field: CoreSchemaOrField,
            current_handler: GetJsonSchemaHandler = current_handler,
            js_modify_function: GetJsonSchemaFunction = js_modify_function,
        ) -> JsonSchemaValue:
            json_schema = js_modify_function(schema_or_field, current_handler)
            if _core_utils.is_core_schema(schema_or_field):
                json_schema = populate_defs(schema_or_field, json_schema)
            original_schema = current_handler.resolve_ref_schema(json_schema)
            ref = json_schema.pop('$ref', None)
            if ref and json_schema:
                original_schema.update(json_schema)
            return original_schema

        current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, new_handler_func)

    for js_modify_function in metadata_handler.metadata.get('pydantic_js_annotation_functions', ()):

        def new_handler_func(
            schema_or_field: CoreSchemaOrField,
            current_handler: GetJsonSchemaHandler = current_handler,
            js_modify_function: GetJsonSchemaFunction = js_modify_function,
        ) -> JsonSchemaValue:
            json_schema = js_modify_function(schema_or_field, current_handler)
            if _core_utils.is_core_schema(schema_or_field):
                json_schema = populate_defs(schema_or_field, json_schema)
                json_schema = convert_to_all_of(json_schema)
            return json_schema

        current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, new_handler_func)

    json_schema = current_handler(schema)
    if _core_utils.is_core_schema(schema):
        json_schema = populate_defs(schema, json_schema)
        json_schema = convert_to_all_of(json_schema)
    return json_schema

any_schema

any_schema(schema: AnySchema) -> JsonSchemaValue

任意の値に一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema AnySchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
540
541
542
543
544
545
546
547
548
549
def any_schema(self, schema: core_schema.AnySchema) -> JsonSchemaValue:
    """任意の値に一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    return {}

none_schema

none_schema(schema: NoneSchema) -> JsonSchemaValue

Generates a JSON schema that matches None.

Parameters:

Name Type Description Default
schema NoneSchema

The core schema.

required

Returns:

Type Description
JsonSchemaValue

The generated JSON schema.

Source code in pydantic/json_schema.py
551
552
553
554
555
556
557
558
559
560
def none_schema(self, schema: core_schema.NoneSchema) -> JsonSchemaValue:
    """Generates a JSON schema that matches `None`.

    Args:
        schema: The core schema.

    Returns:
        The generated JSON schema.
    """
    return {'type': 'null'}

bool_schema

bool_schema(schema: BoolSchema) -> JsonSchemaValue

bool値に一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema BoolSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
562
563
564
565
566
567
568
569
570
571
def bool_schema(self, schema: core_schema.BoolSchema) -> JsonSchemaValue:
    """bool値に一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    return {'type': 'boolean'}

int_schema

int_schema(schema: IntSchema) -> JsonSchemaValue

int値に一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema IntSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
573
574
575
576
577
578
579
580
581
582
583
584
585
def int_schema(self, schema: core_schema.IntSchema) -> JsonSchemaValue:
    """int値に一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    json_schema: dict[str, Any] = {'type': 'integer'}
    self.update_with_validations(json_schema, schema, self.ValidationsMapping.numeric)
    json_schema = {k: v for k, v in json_schema.items() if v not in {math.inf, -math.inf}}
    return json_schema

float_schema

float_schema(schema: FloatSchema) -> JsonSchemaValue

float値に一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema FloatSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
587
588
589
590
591
592
593
594
595
596
597
598
599
def float_schema(self, schema: core_schema.FloatSchema) -> JsonSchemaValue:
    """float値に一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    json_schema: dict[str, Any] = {'type': 'number'}
    self.update_with_validations(json_schema, schema, self.ValidationsMapping.numeric)
    json_schema = {k: v for k, v in json_schema.items() if v not in {math.inf, -math.inf}}
    return json_schema

decimal_schema

decimal_schema(schema: DecimalSchema) -> JsonSchemaValue

decimal値に一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema DecimalSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
def decimal_schema(self, schema: core_schema.DecimalSchema) -> JsonSchemaValue:
    """decimal値に一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    json_schema = self.str_schema(core_schema.str_schema())
    if self.mode == 'validation':
        multiple_of = schema.get('multiple_of')
        le = schema.get('le')
        ge = schema.get('ge')
        lt = schema.get('lt')
        gt = schema.get('gt')
        json_schema = {
            'anyOf': [
                self.float_schema(
                    core_schema.float_schema(
                        allow_inf_nan=schema.get('allow_inf_nan'),
                        multiple_of=None if multiple_of is None else float(multiple_of),
                        le=None if le is None else float(le),
                        ge=None if ge is None else float(ge),
                        lt=None if lt is None else float(lt),
                        gt=None if gt is None else float(gt),
                    )
                ),
                json_schema,
            ],
        }
    return json_schema

str_schema

str_schema(schema: StringSchema) -> JsonSchemaValue

string値に一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema StringSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
def str_schema(self, schema: core_schema.StringSchema) -> JsonSchemaValue:
    """string値に一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    json_schema = {'type': 'string'}
    self.update_with_validations(json_schema, schema, self.ValidationsMapping.string)
    if isinstance(json_schema.get('pattern'), Pattern):
        # TODO: should we add regex flags to the pattern?
        json_schema['pattern'] = json_schema.get('pattern').pattern  # type: ignore
    return json_schema

bytes_schema

bytes_schema(schema: BytesSchema) -> JsonSchemaValue

bytes値に一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema BytesSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
650
651
652
653
654
655
656
657
658
659
660
661
def bytes_schema(self, schema: core_schema.BytesSchema) -> JsonSchemaValue:
    """bytes値に一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    json_schema = {'type': 'string', 'format': 'base64url' if self._config.ser_json_bytes == 'base64' else 'binary'}
    self.update_with_validations(json_schema, schema, self.ValidationsMapping.bytes)
    return json_schema

date_schema

date_schema(schema: DateSchema) -> JsonSchemaValue

date値に一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema DateSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
663
664
665
666
667
668
669
670
671
672
673
674
def date_schema(self, schema: core_schema.DateSchema) -> JsonSchemaValue:
    """date値に一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    json_schema = {'type': 'string', 'format': 'date'}
    self.update_with_validations(json_schema, schema, self.ValidationsMapping.date)
    return json_schema

time_schema

time_schema(schema: TimeSchema) -> JsonSchemaValue

time値に一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema TimeSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
676
677
678
679
680
681
682
683
684
685
def time_schema(self, schema: core_schema.TimeSchema) -> JsonSchemaValue:
    """time値に一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    return {'type': 'string', 'format': 'time'}

datetime_schema

datetime_schema(schema: DatetimeSchema) -> JsonSchemaValue

datetime値に一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema DatetimeSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
687
688
689
690
691
692
693
694
695
696
def datetime_schema(self, schema: core_schema.DatetimeSchema) -> JsonSchemaValue:
    """datetime値に一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    return {'type': 'string', 'format': 'date-time'}

timedelta_schema

timedelta_schema(
    schema: TimedeltaSchema,
) -> JsonSchemaValue

timedelta値に一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema TimedeltaSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
698
699
700
701
702
703
704
705
706
707
708
709
def timedelta_schema(self, schema: core_schema.TimedeltaSchema) -> JsonSchemaValue:
    """timedelta値に一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    if self._config.ser_json_timedelta == 'float':
        return {'type': 'number'}
    return {'type': 'string', 'format': 'duration'}

literal_schema

literal_schema(schema: LiteralSchema) -> JsonSchemaValue

literal値に一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema LiteralSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
def literal_schema(self, schema: core_schema.LiteralSchema) -> JsonSchemaValue:
    """literal値に一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    expected = [v.value if isinstance(v, Enum) else v for v in schema['expected']]
    # jsonify the expected values
    expected = [to_jsonable_python(v) for v in expected]

    result: dict[str, Any] = {'enum': expected}
    if len(expected) == 1:
        result['const'] = expected[0]

    types = {type(e) for e in expected}
    if types == {str}:
        result['type'] = 'string'
    elif types == {int}:
        result['type'] = 'integer'
    elif types == {float}:
        result['type'] = 'numeric'
    elif types == {bool}:
        result['type'] = 'boolean'
    elif types == {list}:
        result['type'] = 'array'
    elif types == {type(None)}:
        result['type'] = 'null'
    return result

enum_schema

enum_schema(schema: EnumSchema) -> JsonSchemaValue

Enum値に一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema EnumSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
def enum_schema(self, schema: core_schema.EnumSchema) -> JsonSchemaValue:
    """Enum値に一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    enum_type = schema['cls']
    description = None if not enum_type.__doc__ else inspect.cleandoc(enum_type.__doc__)
    if (
        description == 'An enumeration.'
    ):  # This is the default value provided by enum.EnumMeta.__new__; don't use it
        description = None
    result: dict[str, Any] = {'title': enum_type.__name__, 'description': description}
    result = {k: v for k, v in result.items() if v is not None}

    expected = [to_jsonable_python(v.value) for v in schema['members']]

    result['enum'] = expected
    if len(expected) == 1:
        result['const'] = expected[0]

    types = {type(e) for e in expected}
    if isinstance(enum_type, str) or types == {str}:
        result['type'] = 'string'
    elif isinstance(enum_type, int) or types == {int}:
        result['type'] = 'integer'
    elif isinstance(enum_type, float) or types == {float}:
        result['type'] = 'numeric'
    elif types == {bool}:
        result['type'] = 'boolean'
    elif types == {list}:
        result['type'] = 'array'

    return result

is_instance_schema

is_instance_schema(
    schema: IsInstanceSchema,
) -> JsonSchemaValue

値がクラスのインスタンスであるかどうかをチェックするコアスキーマのJSONスキーマ生成を処理します。

サブクラスでオーバーライドされない限り、エラーが発生します。

Parameters:

Name Type Description Default
schema IsInstanceSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
781
782
783
784
785
786
787
788
789
790
791
792
def is_instance_schema(self, schema: core_schema.IsInstanceSchema) -> JsonSchemaValue:
    """値がクラスのインスタンスであるかどうかをチェックするコアスキーマのJSONスキーマ生成を処理します。

    サブクラスでオーバーライドされない限り、エラーが発生します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    return self.handle_invalid_for_json_schema(schema, f'core_schema.IsInstanceSchema ({schema["cls"]})')

is_subclass_schema

is_subclass_schema(
    schema: IsSubclassSchema,
) -> JsonSchemaValue

値がクラスのサブクラスであるかどうかをチェックするコアスキーマのJSONスキーマ生成を処理します。

v1との下位互換性のため、これによってエラーが発生することはありませんが、オーバーライドして変更できます。

Parameters:

Name Type Description Default
schema IsSubclassSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
794
795
796
797
798
799
800
801
802
803
804
805
806
807
def is_subclass_schema(self, schema: core_schema.IsSubclassSchema) -> JsonSchemaValue:
    """値がクラスのサブクラスであるかどうかをチェックするコアスキーマのJSONスキーマ生成を処理します。

    v1との下位互換性のため、これによってエラーが発生することはありませんが、オーバーライドして変更できます。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。

    """
    # Note: This is for compatibility with V1; you can override if you want different behavior.
    return {}

callable_schema

callable_schema(schema: CallableSchema) -> JsonSchemaValue

呼び出し可能な値に一致するJSONスキーマを生成します。

サブクラスでオーバーライドされない限り、エラーが発生します。

Parameters:

Name Type Description Default
schema CallableSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
809
810
811
812
813
814
815
816
817
818
819
820
def callable_schema(self, schema: core_schema.CallableSchema) -> JsonSchemaValue:
    """呼び出し可能な値に一致するJSONスキーマを生成します。

    サブクラスでオーバーライドされない限り、エラーが発生します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    return self.handle_invalid_for_json_schema(schema, 'core_schema.CallableSchema')

list_schema

list_schema(schema: ListSchema) -> JsonSchemaValue

リストスキーマに一致するスキーマを返します。

Parameters:

Name Type Description Default
schema ListSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
822
823
824
825
826
827
828
829
830
831
832
833
834
def list_schema(self, schema: core_schema.ListSchema) -> JsonSchemaValue:
    """リストスキーマに一致するスキーマを返します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema'])
    json_schema = {'type': 'array', 'items': items_schema}
    self.update_with_validations(json_schema, schema, self.ValidationsMapping.array)
    return json_schema

tuple_positional_schema

tuple_positional_schema(
    schema: TupleSchema,
) -> JsonSchemaValue

Replaced by tuple_schema.

Source code in pydantic/json_schema.py
836
837
838
839
840
841
842
843
844
845
@deprecated('`tuple_positional_schema` is deprecated. Use `tuple_schema` instead.', category=None)
@final
def tuple_positional_schema(self, schema: core_schema.TupleSchema) -> JsonSchemaValue:
    """Replaced by `tuple_schema`."""
    warnings.warn(
        '`tuple_positional_schema` is deprecated. Use `tuple_schema` instead.',
        PydanticDeprecatedSince26,
        stacklevel=2,
    )
    return self.tuple_schema(schema)

tuple_variable_schema

tuple_variable_schema(
    schema: TupleSchema,
) -> JsonSchemaValue

Replaced by tuple_schema.

Source code in pydantic/json_schema.py
847
848
849
850
851
852
853
854
855
856
@deprecated('`tuple_variable_schema` is deprecated. Use `tuple_schema` instead.', category=None)
@final
def tuple_variable_schema(self, schema: core_schema.TupleSchema) -> JsonSchemaValue:
    """Replaced by `tuple_schema`."""
    warnings.warn(
        '`tuple_variable_schema` is deprecated. Use `tuple_schema` instead.',
        PydanticDeprecatedSince26,
        stacklevel=2,
    )
    return self.tuple_schema(schema)

tuple_schema

tuple_schema(schema: TupleSchema) -> JsonSchemaValue

タプルスキーマに一致するJSONスキーマを生成します。例えば、Tuple[int, str, bool]Tuple[int, .]などです。

Parameters:

Name Type Description Default
schema TupleSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
def tuple_schema(self, schema: core_schema.TupleSchema) -> JsonSchemaValue:
    """タプルスキーマに一致するJSONスキーマを生成します。例えば、`Tuple[int, str, bool]`や`Tuple[int, .]`などです。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    json_schema: JsonSchemaValue = {'type': 'array'}
    if 'variadic_item_index' in schema:
        variadic_item_index = schema['variadic_item_index']
        if variadic_item_index > 0:
            json_schema['minItems'] = variadic_item_index
            json_schema['prefixItems'] = [
                self.generate_inner(item) for item in schema['items_schema'][:variadic_item_index]
            ]
        if variadic_item_index + 1 == len(schema['items_schema']):
            # if the variadic item is the last item, then represent it faithfully
            json_schema['items'] = self.generate_inner(schema['items_schema'][variadic_item_index])
        else:
            # otherwise, 'items' represents the schema for the variadic
            # item plus the suffix, so just allow anything for simplicity
            # for now
            json_schema['items'] = True
    else:
        prefixItems = [self.generate_inner(item) for item in schema['items_schema']]
        if prefixItems:
            json_schema['prefixItems'] = prefixItems
        json_schema['minItems'] = len(prefixItems)
        json_schema['maxItems'] = len(prefixItems)
    self.update_with_validations(json_schema, schema, self.ValidationsMapping.array)
    return json_schema

set_schema

set_schema(schema: SetSchema) -> JsonSchemaValue

setスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema SetSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
892
893
894
895
896
897
898
899
900
901
def set_schema(self, schema: core_schema.SetSchema) -> JsonSchemaValue:
    """setスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    return self._common_set_schema(schema)

frozenset_schema

frozenset_schema(
    schema: FrozenSetSchema,
) -> JsonSchemaValue

frozensetスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema FrozenSetSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
903
904
905
906
907
908
909
910
911
912
def frozenset_schema(self, schema: core_schema.FrozenSetSchema) -> JsonSchemaValue:
    """frozensetスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    return self._common_set_schema(schema)

generator_schema

generator_schema(
    schema: GeneratorSchema,
) -> JsonSchemaValue

指定されたGeneratorSchemaを表すJSONスキーマを返します。

Parameters:

Name Type Description Default
schema GeneratorSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
920
921
922
923
924
925
926
927
928
929
930
931
932
def generator_schema(self, schema: core_schema.GeneratorSchema) -> JsonSchemaValue:
    """指定されたGeneratorSchemaを表すJSONスキーマを返します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema'])
    json_schema = {'type': 'array', 'items': items_schema}
    self.update_with_validations(json_schema, schema, self.ValidationsMapping.array)
    return json_schema

dict_schema

dict_schema(schema: DictSchema) -> JsonSchemaValue

dictスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema DictSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
def dict_schema(self, schema: core_schema.DictSchema) -> JsonSchemaValue:
    """dictスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    json_schema: JsonSchemaValue = {'type': 'object'}

    keys_schema = self.generate_inner(schema['keys_schema']).copy() if 'keys_schema' in schema else {}
    keys_pattern = keys_schema.pop('pattern', None)

    values_schema = self.generate_inner(schema['values_schema']).copy() if 'values_schema' in schema else {}
    values_schema.pop('title', None)  # don't give a title to the additionalProperties
    if values_schema or keys_pattern is not None:  # don't add additionalProperties if it's empty
        if keys_pattern is None:
            json_schema['additionalProperties'] = values_schema
        else:
            json_schema['patternProperties'] = {keys_pattern: values_schema}

    self.update_with_validations(json_schema, schema, self.ValidationsMapping.object)
    return json_schema

function_before_schema

function_before_schema(
    schema: BeforeValidatorFunctionSchema,
) -> JsonSchemaValue

function-beforeスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema BeforeValidatorFunctionSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
973
974
975
976
977
978
979
980
981
982
def function_before_schema(self, schema: core_schema.BeforeValidatorFunctionSchema) -> JsonSchemaValue:
    """function-beforeスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    return self._function_schema(schema)

function_after_schema

function_after_schema(
    schema: AfterValidatorFunctionSchema,
) -> JsonSchemaValue

function-afterスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema AfterValidatorFunctionSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
984
985
986
987
988
989
990
991
992
993
def function_after_schema(self, schema: core_schema.AfterValidatorFunctionSchema) -> JsonSchemaValue:
    """function-afterスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    return self._function_schema(schema)

function_plain_schema

function_plain_schema(
    schema: PlainValidatorFunctionSchema,
) -> JsonSchemaValue

function-plainスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema PlainValidatorFunctionSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
def function_plain_schema(self, schema: core_schema.PlainValidatorFunctionSchema) -> JsonSchemaValue:
    """function-plainスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    return self._function_schema(schema)

function_wrap_schema

function_wrap_schema(
    schema: WrapValidatorFunctionSchema,
) -> JsonSchemaValue

function-wrapスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema WrapValidatorFunctionSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
def function_wrap_schema(self, schema: core_schema.WrapValidatorFunctionSchema) -> JsonSchemaValue:
    """function-wrapスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    return self._function_schema(schema)

default_schema

default_schema(
    schema: WithDefaultSchema,
) -> JsonSchemaValue

デフォルト値を持つスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema WithDefaultSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
def default_schema(self, schema: core_schema.WithDefaultSchema) -> JsonSchemaValue:
    """デフォルト値を持つスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    json_schema = self.generate_inner(schema['schema'])

    if 'default' not in schema:
        return json_schema
    default = schema['default']
    # Note: if you want to include the value returned by the default_factory,
    # override this method and replace the code above with:
    # if 'default' in schema:
    #     default = schema['default']
    # elif 'default_factory' in schema:
    #     default = schema['default_factory']()
    # else:
    #     return json_schema

    # we reflect the application of custom plain, no-info serializers to defaults for
    # json schemas viewed in serialization mode
    # TODO: improvements along with https://github.com/pydantic/pydantic/issues/8208
    # TODO: improve type safety here
    if self.mode == 'serialization':
        if (
            (ser_schema := schema['schema'].get('serialization', {}))
            and (ser_func := ser_schema.get('function'))
            and ser_schema.get('type') == 'function-plain'  # type: ignore
            and ser_schema.get('info_arg') is False  # type: ignore
        ):
            default = ser_func(default)  # type: ignore

    try:
        encoded_default = self.encode_default(default)
    except pydantic_core.PydanticSerializationError:
        self.emit_warning(
            'non-serializable-default',
            f'Default value {default} is not JSON serializable; excluding default from JSON schema',
        )
        # Return the inner schema, as though there was no default
        return json_schema

    if '$ref' in json_schema:
        # Since reference schemas do not support child keys, we wrap the reference schema in a single-case allOf:
        return {'allOf': [json_schema], 'default': encoded_default}
    else:
        json_schema['default'] = encoded_default
        return json_schema

nullable_schema

nullable_schema(schema: NullableSchema) -> JsonSchemaValue

null値を許可するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema NullableSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
def nullable_schema(self, schema: core_schema.NullableSchema) -> JsonSchemaValue:
    """null値を許可するスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    null_schema = {'type': 'null'}
    inner_json_schema = self.generate_inner(schema['schema'])

    if inner_json_schema == null_schema:
        return null_schema
    else:
        # Thanks to the equality check against `null_schema` above, I think 'oneOf' would also be valid here;
        # I'll use 'anyOf' for now, but it could be changed it if it would work better with some external tooling
        return self.get_flattened_anyof([inner_json_schema, null_schema])

union_schema

union_schema(schema: UnionSchema) -> JsonSchemaValue

指定されたスキーマのいずれかに一致する値を許可するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema UnionSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
def union_schema(self, schema: core_schema.UnionSchema) -> JsonSchemaValue:
    """指定されたスキーマのいずれかに一致する値を許可するスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。

    """
    generated: list[JsonSchemaValue] = []

    choices = schema['choices']
    for choice in choices:
        # choice will be a tuple if an explicit label was provided
        choice_schema = choice[0] if isinstance(choice, tuple) else choice
        try:
            generated.append(self.generate_inner(choice_schema))
        except PydanticOmit:
            continue
        except PydanticInvalidForJsonSchema as exc:
            self.emit_warning('skipped-choice', exc.message)
    if len(generated) == 1:
        return generated[0]
    return self.get_flattened_anyof(generated)

tagged_union_schema

tagged_union_schema(
    schema: TaggedUnionSchema,
) -> JsonSchemaValue

指定されたスキーマのいずれかに一致する値を許可するスキーマに一致するJSONスキーマを生成します。スキーマには、値の検証に使用するスキーマを示す識別子フィールドのタグが付けられます。

Parameters:

Name Type Description Default
schema TaggedUnionSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
def tagged_union_schema(self, schema: core_schema.TaggedUnionSchema) -> JsonSchemaValue:
    """指定されたスキーマのいずれかに一致する値を許可するスキーマに一致するJSONスキーマを生成します。スキーマには、値の検証に使用するスキーマを示す識別子フィールドのタグが付けられます。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    generated: dict[str, JsonSchemaValue] = {}
    for k, v in schema['choices'].items():
        if isinstance(k, Enum):
            k = k.value
        try:
            # Use str(k) since keys must be strings for json; while not technically correct,
            # it's the closest that can be represented in valid JSON
            generated[str(k)] = self.generate_inner(v).copy()
        except PydanticOmit:
            continue
        except PydanticInvalidForJsonSchema as exc:
            self.emit_warning('skipped-choice', exc.message)

    one_of_choices = _deduplicate_schemas(generated.values())
    json_schema: JsonSchemaValue = {'oneOf': one_of_choices}

    # This reflects the v1 behavior; TODO: we should make it possible to exclude OpenAPI stuff from the JSON schema
    openapi_discriminator = self._extract_discriminator(schema, one_of_choices)
    if openapi_discriminator is not None:
        json_schema['discriminator'] = {
            'propertyName': openapi_discriminator,
            'mapping': {k: v.get('$ref', v) for k, v in generated.items()},
        }

    return json_schema

chain_schema

chain_schema(schema: ChainSchema) -> JsonSchemaValue

core_schema.ChainSchemaに一致するJSONスキーマを生成します。

検証のためのスキーマを生成するとき、チェーンの最初のステップの検証JSONスキーマを返します。 シリアライゼーションでは、チェーンの最後のステップのシリアライゼーションJSONスキーマを返します。

Parameters:

Name Type Description Default
schema ChainSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
def chain_schema(self, schema: core_schema.ChainSchema) -> JsonSchemaValue:
    """core_schema.ChainSchemaに一致するJSONスキーマを生成します。

    検証のためのスキーマを生成するとき、チェーンの最初のステップの検証JSONスキーマを返します。
    シリアライゼーションでは、チェーンの最後のステップのシリアライゼーションJSONスキーマを返します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    step_index = 0 if self.mode == 'validation' else -1  # use first step for validation, last for serialization
    return self.generate_inner(schema['steps'][step_index])

lax_or_strict_schema

lax_or_strict_schema(
    schema: LaxOrStrictSchema,
) -> JsonSchemaValue

laxスキーマまたはstrictスキーマのいずれかに一致する値を許可するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema LaxOrStrictSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
def lax_or_strict_schema(self, schema: core_schema.LaxOrStrictSchema) -> JsonSchemaValue:
    """laxスキーマまたはstrictスキーマのいずれかに一致する値を許可するスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    # TODO: Need to read the default value off of model config or whatever
    use_strict = schema.get('strict', False)  # TODO: replace this default False
    # If your JSON schema fails to generate it is probably
    # because one of the following two branches failed.
    if use_strict:
        return self.generate_inner(schema['strict_schema'])
    else:
        return self.generate_inner(schema['lax_schema'])

json_or_python_schema

json_or_python_schema(
    schema: JsonOrPythonSchema,
) -> JsonSchemaValue

JSONスキーマまたはPythonスキーマのいずれかに一致する値を許可するスキーマに一致するJSONスキーマを生成します。

Pythonスキーマの代わりにJSONスキーマが使用されます。Pythonスキーマを使用する場合は、このメソッドをオーバーライドする必要があります。

Parameters:

Name Type Description Default
schema JsonOrPythonSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
def json_or_python_schema(self, schema: core_schema.JsonOrPythonSchema) -> JsonSchemaValue:
    """JSONスキーマまたはPythonスキーマのいずれかに一致する値を許可するスキーマに一致するJSONスキーマを生成します。

    Pythonスキーマの代わりにJSONスキーマが使用されます。Pythonスキーマを使用する場合は、このメソッドをオーバーライドする必要があります。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    return self.generate_inner(schema['json_schema'])

typed_dict_schema

typed_dict_schema(
    schema: TypedDictSchema,
) -> JsonSchemaValue

型付きdictを定義するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema TypedDictSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
def typed_dict_schema(self, schema: core_schema.TypedDictSchema) -> JsonSchemaValue:
    """型付きdictを定義するスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    total = schema.get('total', True)
    named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [
        (name, self.field_is_required(field, total), field)
        for name, field in schema['fields'].items()
        if self.field_is_present(field)
    ]
    if self.mode == 'serialization':
        named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', [])))
    cls = _get_typed_dict_cls(schema)
    config = _get_typed_dict_config(cls)
    with self._config_wrapper_stack.push(config):
        json_schema = self._named_required_fields_schema(named_required_fields)

    json_schema_extra = config.get('json_schema_extra')
    extra = schema.get('extra_behavior')
    if extra is None:
        extra = config.get('extra', 'ignore')

    if cls is not None:
        title = config.get('title') or cls.__name__
        json_schema = self._update_class_schema(json_schema, title, extra, cls, json_schema_extra)
    else:
        if extra == 'forbid':
            json_schema['additionalProperties'] = False
        elif extra == 'allow':
            json_schema['additionalProperties'] = True

    return json_schema

typed_dict_field_schema

typed_dict_field_schema(
    schema: TypedDictField,
) -> JsonSchemaValue

型指定されたdictフィールドを定義するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema TypedDictField

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
def typed_dict_field_schema(self, schema: core_schema.TypedDictField) -> JsonSchemaValue:
    """型指定されたdictフィールドを定義するスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。

    """
    return self.generate_inner(schema['schema'])

dataclass_field_schema

dataclass_field_schema(
    schema: DataclassField,
) -> JsonSchemaValue

データクラスフィールドを定義するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema DataclassField

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
def dataclass_field_schema(self, schema: core_schema.DataclassField) -> JsonSchemaValue:
    """データクラスフィールドを定義するスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    return self.generate_inner(schema['schema'])

model_field_schema

model_field_schema(schema: ModelField) -> JsonSchemaValue

モデルフィールドを定義するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema ModelField

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
def model_field_schema(self, schema: core_schema.ModelField) -> JsonSchemaValue:
    """モデルフィールドを定義するスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    return self.generate_inner(schema['schema'])

computed_field_schema

computed_field_schema(
    schema: ComputedField,
) -> JsonSchemaValue

計算フィールドを定義するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema ComputedField

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
def computed_field_schema(self, schema: core_schema.ComputedField) -> JsonSchemaValue:
    """計算フィールドを定義するスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    return self.generate_inner(schema['return_schema'])

model_schema

model_schema(schema: ModelSchema) -> JsonSchemaValue

モデルを定義するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema ModelSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
def model_schema(self, schema: core_schema.ModelSchema) -> JsonSchemaValue:
    """モデルを定義するスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    # We do not use schema['model'].model_json_schema() here
    # because it could lead to inconsistent refs handling, etc.
    cls = cast('type[BaseModel]', schema['cls'])
    config = cls.model_config
    title = config.get('title')

    with self._config_wrapper_stack.push(config):
        json_schema = self.generate_inner(schema['schema'])

    json_schema_extra = config.get('json_schema_extra')
    if cls.__pydantic_root_model__:
        root_json_schema_extra = cls.model_fields['root'].json_schema_extra
        if json_schema_extra and root_json_schema_extra:
            raise ValueError(
                '"model_config[\'json_schema_extra\']" and "Field.json_schema_extra" on "RootModel.root"'
                ' field must not be set simultaneously'
            )
        if root_json_schema_extra:
            json_schema_extra = root_json_schema_extra

    json_schema = self._update_class_schema(json_schema, title, config.get('extra', None), cls, json_schema_extra)

    return json_schema

resolve_schema_to_update

resolve_schema_to_update(
    json_schema: JsonSchemaValue,
) -> JsonSchemaValue

JsonSchemaValueが$refスキーマである場合は、非refスキーマに解決します。

Parameters:

Name Type Description Default
json_schema JsonSchemaValue

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
def resolve_schema_to_update(self, json_schema: JsonSchemaValue) -> JsonSchemaValue:
    """JsonSchemaValueが$refスキーマである場合は、非refスキーマに解決します。

    Args:
        json_schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    if '$ref' in json_schema:
        schema_to_update = self.get_schema_from_definitions(JsonRef(json_schema['$ref']))
        if schema_to_update is None:
            raise RuntimeError(f'Cannot update undefined schema for $ref={json_schema["$ref"]}')
        return self.resolve_schema_to_update(schema_to_update)
    else:
        schema_to_update = json_schema
    return schema_to_update

model_fields_schema

model_fields_schema(
    schema: ModelFieldsSchema,
) -> JsonSchemaValue

モデルのフィールドを定義するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema ModelFieldsSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
def model_fields_schema(self, schema: core_schema.ModelFieldsSchema) -> JsonSchemaValue:
    """モデルのフィールドを定義するスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [
        (name, self.field_is_required(field, total=True), field)
        for name, field in schema['fields'].items()
        if self.field_is_present(field)
    ]
    if self.mode == 'serialization':
        named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', [])))
    json_schema = self._named_required_fields_schema(named_required_fields)
    extras_schema = schema.get('extras_schema', None)
    if extras_schema is not None:
        schema_to_update = self.resolve_schema_to_update(json_schema)
        schema_to_update['additionalProperties'] = self.generate_inner(extras_schema)
    return json_schema

field_is_present

field_is_present(field: CoreSchemaField) -> bool

生成されたJSONスキーマにフィールドを含めるかどうか。

Parameters:

Name Type Description Default
field CoreSchemaField

フィールド自体のスキーマ。

required

Returns:

Type Description
bool

フィールドが生成されたJSONスキーマに含まれる場合はTrue、含まれない場合はFalse。

Source code in pydantic/json_schema.py
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
def field_is_present(self, field: CoreSchemaField) -> bool:
    """生成されたJSONスキーマにフィールドを含めるかどうか。

    Args:
        field: フィールド自体のスキーマ。

    Returns:
        フィールドが生成されたJSONスキーマに含まれる場合はTrue、含まれない場合はFalse。
    """
    if self.mode == 'serialization':
        # If you still want to include the field in the generated JSON schema,
        # override this method and return True
        return not field.get('serialization_exclude')
    elif self.mode == 'validation':
        return True
    else:
        assert_never(self.mode)

field_is_required

field_is_required(
    field: ModelField | DataclassField | TypedDictField,
    total: bool,
) -> bool

生成されたJSONスキーマでフィールドが必須としてマークされるかどうか。 (フィールドがJSONスキーマに存在しない場合、これは無関係であることに注意してください。

Parameters:

Name Type Description Default
field ModelField | DataclassField | TypedDictField

フィールド自体のスキーマ。

required
total bool

TypedDictFieldにのみ適用されます。 このフィールドが属するTypedDictが合計かどうかを示します。この場合、required=Falseを明示的に指定していないフィールドはすべて必要です。

required

Returns:

Type Description
bool

生成されたJSONスキーマでフィールドがrequiredとマークされる場合はTrue、それ以外の場合はFalseです。

Source code in pydantic/json_schema.py
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
def field_is_required(
    self,
    field: core_schema.ModelField | core_schema.DataclassField | core_schema.TypedDictField,
    total: bool,
) -> bool:
    """生成されたJSONスキーマでフィールドが必須としてマークされるかどうか。
    (フィールドがJSONスキーマに存在しない場合、これは無関係であることに注意してください。

    Args:
        field: フィールド自体のスキーマ。
        total: `TypedDictField`にのみ適用されます。
            このフィールドが属する`TypedDict`が合計かどうかを示します。この場合、`required=False`を明示的に指定していないフィールドはすべて必要です。

    Returns:
        生成されたJSONスキーマでフィールドがrequiredとマークされる場合は`True`、それ以外の場合は`False`です。
    """
    if self.mode == 'serialization' and self._config.json_schema_serialization_defaults_required:
        return not field.get('serialization_exclude')
    else:
        if field['type'] == 'typed-dict-field':
            return field.get('required', total)
        else:
            return field['schema']['type'] != 'default'

dataclass_args_schema

dataclass_args_schema(
    schema: DataclassArgsSchema,
) -> JsonSchemaValue

データクラスのコンストラクタ引数を定義するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema DataclassArgsSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
def dataclass_args_schema(self, schema: core_schema.DataclassArgsSchema) -> JsonSchemaValue:
    """データクラスのコンストラクタ引数を定義するスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [
        (field['name'], self.field_is_required(field, total=True), field)
        for field in schema['fields']
        if self.field_is_present(field)
    ]
    if self.mode == 'serialization':
        named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', [])))
    return self._named_required_fields_schema(named_required_fields)

dataclass_schema

dataclass_schema(
    schema: DataclassSchema,
) -> JsonSchemaValue

データクラスを定義するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema DataclassSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
def dataclass_schema(self, schema: core_schema.DataclassSchema) -> JsonSchemaValue:
    """データクラスを定義するスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    cls = schema['cls']
    config: ConfigDict = getattr(cls, '__pydantic_config__', cast('ConfigDict', {}))
    title = config.get('title') or cls.__name__

    with self._config_wrapper_stack.push(config):
        json_schema = self.generate_inner(schema['schema']).copy()

    json_schema_extra = config.get('json_schema_extra')
    json_schema = self._update_class_schema(json_schema, title, config.get('extra', None), cls, json_schema_extra)

    # Dataclass-specific handling of description
    if is_dataclass(cls) and not hasattr(cls, '__pydantic_validator__'):
        # vanilla dataclass; don't use cls.__doc__ as it will contain the class signature by default
        description = None
    else:
        description = None if cls.__doc__ is None else inspect.cleandoc(cls.__doc__)
    if description:
        json_schema['description'] = description

    return json_schema

arguments_schema

arguments_schema(
    schema: ArgumentsSchema,
) -> JsonSchemaValue

関数の引数を定義するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema ArgumentsSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
def arguments_schema(self, schema: core_schema.ArgumentsSchema) -> JsonSchemaValue:
    """関数の引数を定義するスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    metadata = _core_metadata.CoreMetadataHandler(schema).metadata
    prefer_positional = metadata.get('pydantic_js_prefer_positional_arguments')

    arguments = schema['arguments_schema']
    kw_only_arguments = [a for a in arguments if a.get('mode') == 'keyword_only']
    kw_or_p_arguments = [a for a in arguments if a.get('mode') in {'positional_or_keyword', None}]
    p_only_arguments = [a for a in arguments if a.get('mode') == 'positional_only']
    var_args_schema = schema.get('var_args_schema')
    var_kwargs_schema = schema.get('var_kwargs_schema')

    if prefer_positional:
        positional_possible = not kw_only_arguments and not var_kwargs_schema
        if positional_possible:
            return self.p_arguments_schema(p_only_arguments + kw_or_p_arguments, var_args_schema)

    keyword_possible = not p_only_arguments and not var_args_schema
    if keyword_possible:
        return self.kw_arguments_schema(kw_or_p_arguments + kw_only_arguments, var_kwargs_schema)

    if not prefer_positional:
        positional_possible = not kw_only_arguments and not var_kwargs_schema
        if positional_possible:
            return self.p_arguments_schema(p_only_arguments + kw_or_p_arguments, var_args_schema)

    raise PydanticInvalidForJsonSchema(
        'Unable to generate JSON schema for arguments validator with positional-only and keyword-only arguments'
    )

kw_arguments_schema

kw_arguments_schema(
    arguments: list[ArgumentsParameter],
    var_kwargs_schema: CoreSchema | None,
) -> JsonSchemaValue

関数のキーワード引数を定義するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
arguments list[ArgumentsParameter]

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
def kw_arguments_schema(
    self, arguments: list[core_schema.ArgumentsParameter], var_kwargs_schema: CoreSchema | None
) -> JsonSchemaValue:
    """関数のキーワード引数を定義するスキーマに一致するJSONスキーマを生成します。

    Args:
        arguments: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    properties: dict[str, JsonSchemaValue] = {}
    required: list[str] = []
    for argument in arguments:
        name = self.get_argument_name(argument)
        argument_schema = self.generate_inner(argument['schema']).copy()
        argument_schema['title'] = self.get_title_from_name(name)
        properties[name] = argument_schema

        if argument['schema']['type'] != 'default':
            # This assumes that if the argument has a default value,
            # the inner schema must be of type WithDefaultSchema.
            # I believe this is true, but I am not 100% sure
            required.append(name)

    json_schema: JsonSchemaValue = {'type': 'object', 'properties': properties}
    if required:
        json_schema['required'] = required

    if var_kwargs_schema:
        additional_properties_schema = self.generate_inner(var_kwargs_schema)
        if additional_properties_schema:
            json_schema['additionalProperties'] = additional_properties_schema
    else:
        json_schema['additionalProperties'] = False
    return json_schema

p_arguments_schema

p_arguments_schema(
    arguments: list[ArgumentsParameter],
    var_args_schema: CoreSchema | None,
) -> JsonSchemaValue

関数の位置引数を定義するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
arguments list[ArgumentsParameter]

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
def p_arguments_schema(
    self, arguments: list[core_schema.ArgumentsParameter], var_args_schema: CoreSchema | None
) -> JsonSchemaValue:
    """関数の位置引数を定義するスキーマに一致するJSONスキーマを生成します。

    Args:
        arguments: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    prefix_items: list[JsonSchemaValue] = []
    min_items = 0

    for argument in arguments:
        name = self.get_argument_name(argument)

        argument_schema = self.generate_inner(argument['schema']).copy()
        argument_schema['title'] = self.get_title_from_name(name)
        prefix_items.append(argument_schema)

        if argument['schema']['type'] != 'default':
            # This assumes that if the argument has a default value,
            # the inner schema must be of type WithDefaultSchema.
            # I believe this is true, but I am not 100% sure
            min_items += 1

    json_schema: JsonSchemaValue = {'type': 'array', 'prefixItems': prefix_items}
    if min_items:
        json_schema['minItems'] = min_items

    if var_args_schema:
        items_schema = self.generate_inner(var_args_schema)
        if items_schema:
            json_schema['items'] = items_schema
    else:
        json_schema['maxItems'] = len(prefix_items)

    return json_schema

get_argument_name

get_argument_name(argument: ArgumentsParameter) -> str

引数の名前を取得します。

Parameters:

Name Type Description Default
argument ArgumentsParameter

コア・スキーマ。

required

Returns:

Type Description
str

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
def get_argument_name(self, argument: core_schema.ArgumentsParameter) -> str:
    """引数の名前を取得します。

    Args:
        argument: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    name = argument['name']
    if self.by_alias:
        alias = argument.get('alias')
        if isinstance(alias, str):
            name = alias
        else:
            pass  # might want to do something else?
    return name

call_schema

call_schema(schema: CallSchema) -> JsonSchemaValue

関数呼び出しを定義するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema CallSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
def call_schema(self, schema: core_schema.CallSchema) -> JsonSchemaValue:
    """関数呼び出しを定義するスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    return self.generate_inner(schema['arguments_schema'])

custom_error_schema

custom_error_schema(
    schema: CustomErrorSchema,
) -> JsonSchemaValue

カスタムエラーを定義するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema CustomErrorSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
def custom_error_schema(self, schema: core_schema.CustomErrorSchema) -> JsonSchemaValue:
    """カスタムエラーを定義するスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    return self.generate_inner(schema['schema'])

json_schema

json_schema(schema: JsonSchema) -> JsonSchemaValue

JSONオブジェクトを定義するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema JsonSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
def json_schema(self, schema: core_schema.JsonSchema) -> JsonSchemaValue:
    """JSONオブジェクトを定義するスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    content_core_schema = schema.get('schema') or core_schema.any_schema()
    content_json_schema = self.generate_inner(content_core_schema)
    if self.mode == 'validation':
        return {'type': 'string', 'contentMediaType': 'application/json', 'contentSchema': content_json_schema}
    else:
        # self.mode == 'serialization'
        return content_json_schema

url_schema

url_schema(schema: UrlSchema) -> JsonSchemaValue

URLを定義するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema UrlSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
def url_schema(self, schema: core_schema.UrlSchema) -> JsonSchemaValue:
    """URLを定義するスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    json_schema = {'type': 'string', 'format': 'uri', 'minLength': 1}
    self.update_with_validations(json_schema, schema, self.ValidationsMapping.string)
    return json_schema

multi_host_url_schema

multi_host_url_schema(
    schema: MultiHostUrlSchema,
) -> JsonSchemaValue

複数のホストで使用できるURLを定義するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema MultiHostUrlSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
def multi_host_url_schema(self, schema: core_schema.MultiHostUrlSchema) -> JsonSchemaValue:
    """複数のホストで使用できるURLを定義するスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    # Note: 'multi-host-uri' is a custom/pydantic-specific format, not part of the JSON Schema spec
    json_schema = {'type': 'string', 'format': 'multi-host-uri', 'minLength': 1}
    self.update_with_validations(json_schema, schema, self.ValidationsMapping.string)
    return json_schema

uuid_schema

uuid_schema(schema: UuidSchema) -> JsonSchemaValue

UUIDに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema UuidSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
def uuid_schema(self, schema: core_schema.UuidSchema) -> JsonSchemaValue:
    """UUIDに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    return {'type': 'string', 'format': 'uuid'}

definitions_schema

definitions_schema(
    schema: DefinitionsSchema,
) -> JsonSchemaValue

定義を持つJSONオブジェクトを定義するスキーマと一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema DefinitionsSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
def definitions_schema(self, schema: core_schema.DefinitionsSchema) -> JsonSchemaValue:
    """定義を持つJSONオブジェクトを定義するスキーマと一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    for definition in schema['definitions']:
        try:
            self.generate_inner(definition)
        except PydanticInvalidForJsonSchema as e:
            core_ref: CoreRef = CoreRef(definition['ref'])  # type: ignore
            self._core_defs_invalid_for_json_schema[self.get_defs_ref((core_ref, self.mode))] = e
            continue
    return self.generate_inner(schema['schema'])

definition_ref_schema

definition_ref_schema(
    schema: DefinitionReferenceSchema,
) -> JsonSchemaValue

定義を参照するスキーマに一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema DefinitionReferenceSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
def definition_ref_schema(self, schema: core_schema.DefinitionReferenceSchema) -> JsonSchemaValue:
    """定義を参照するスキーマに一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    core_ref = CoreRef(schema['schema_ref'])
    _, ref_json_schema = self.get_cache_defs_ref_schema(core_ref)
    return ref_json_schema

ser_schema

ser_schema(
    schema: (
        SerSchema | IncExSeqSerSchema | IncExDictSerSchema
    ),
) -> JsonSchemaValue | None

シリアライズされたオブジェクトを定義するスキーマと一致するJSONスキーマを生成します。

Parameters:

Name Type Description Default
schema SerSchema | IncExSeqSerSchema | IncExDictSerSchema

コア・スキーマ。

required

Returns:

Type Description
JsonSchemaValue | None

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
def ser_schema(
    self, schema: core_schema.SerSchema | core_schema.IncExSeqSerSchema | core_schema.IncExDictSerSchema
) -> JsonSchemaValue | None:
    """シリアライズされたオブジェクトを定義するスキーマと一致するJSONスキーマを生成します。

    Args:
        schema: コア・スキーマ。

    Returns:
        生成されたJSONスキーマ。
    """
    schema_type = schema['type']
    if schema_type == 'function-plain' or schema_type == 'function-wrap':
        # PlainSerializerFunctionSerSchema or WrapSerializerFunctionSerSchema
        return_schema = schema.get('return_schema')
        if return_schema is not None:
            return self.generate_inner(return_schema)
    elif schema_type == 'format' or schema_type == 'to-string':
        # FormatSerSchema or ToStringSerSchema
        return self.str_schema(core_schema.str_schema())
    elif schema['type'] == 'model':
        # ModelSerSchema
        return self.generate_inner(schema['schema'])
    return None

get_title_from_name

get_title_from_name(name: str) -> str

引数名を取得します。

Parameters:

Name Type Description Default
name str

タイトルの取得元の名前。

required

Returns:

Type Description
str

引数名。

Source code in pydantic/json_schema.py
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
def get_title_from_name(self, name: str) -> str:
    """引数名を取得します。

    Args:
        name: タイトルの取得元の名前。

    Returns:
        引数名。
    """
    return name.title().replace('_', ' ')

field_title_should_be_set

field_title_should_be_set(
    schema: CoreSchemaOrField,
) -> bool

指定されたスキーマを持つフィールドに、フィールド名に基づいたタイトルセットが必要な場合、trueを返します。

直感的には、他の方法では独自のタイトルを提供しないスキーマ(int、float、strなど)に対してはtrueを返し、独自のタイトルを提供するスキーマ(BaseModelサブクラスなど)に対してはfalseを返すようにします。

Parameters:

Name Type Description Default
schema CoreSchemaOrField

チェックするスキーマ。

required

Returns:

Type Description
bool

フィールドにタイトルを設定する必要がある場合はTrue、そうでない場合はFalseです。

Source code in pydantic/json_schema.py
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
def field_title_should_be_set(self, schema: CoreSchemaOrField) -> bool:
    """指定されたスキーマを持つフィールドに、フィールド名に基づいたタイトルセットが必要な場合、trueを返します。

    直感的には、他の方法では独自のタイトルを提供しないスキーマ(int、float、strなど)に対してはtrueを返し、独自のタイトルを提供するスキーマ(BaseModelサブクラスなど)に対してはfalseを返すようにします。

    Args:
        schema: チェックするスキーマ。

    Returns:
        フィールドにタイトルを設定する必要がある場合は`True`、そうでない場合は`False`です。
    """
    if _core_utils.is_core_schema_field(schema):
        if schema['type'] == 'computed-field':
            field_schema = schema['return_schema']
        else:
            field_schema = schema['schema']
        return self.field_title_should_be_set(field_schema)

    elif _core_utils.is_core_schema(schema):
        if schema.get('ref'):  # things with refs, such as models and enums, should not have titles set
            return False
        if schema['type'] in {'default', 'nullable', 'definitions'}:
            return self.field_title_should_be_set(schema['schema'])  # type: ignore[typeddict-item]
        if _core_utils.is_function_with_inner_schema(schema):
            return self.field_title_should_be_set(schema['schema'])
        if schema['type'] == 'definition-ref':
            # Referenced schemas should not have titles set for the same reason
            # schemas with refs should not
            return False
        return True  # anything else should have title set

    else:
        raise PydanticInvalidForJsonSchema(f'Unexpected schema type: schema={schema}')  # pragma: no cover

normalize_name

normalize_name(name: str) -> str

名前を正規化して、辞書のキーとして使用します。

Parameters:

Name Type Description Default
name str

正規化する名前。

required

Returns:

Type Description
str

正規化された名前。

Source code in pydantic/json_schema.py
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
def normalize_name(self, name: str) -> str:
    """名前を正規化して、辞書のキーとして使用します。

    Args:
        name: 正規化する名前。

    Returns:
        正規化された名前。
    """
    return re.sub(r'[^a-zA-Z0-9.\-_]', '_', name).replace('.', '__')

get_defs_ref

get_defs_ref(core_mode_ref: CoreModeRef) -> DefsRef

このメソッドをオーバーライドして、コア参照から定義キーを生成する方法を変更します。

Parameters:

Name Type Description Default
core_mode_ref CoreModeRef

コアへの参照。

required

Returns:

Type Description
DefsRef

定義キー。

Source code in pydantic/json_schema.py
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
def get_defs_ref(self, core_mode_ref: CoreModeRef) -> DefsRef:
    """このメソッドをオーバーライドして、コア参照から定義キーを生成する方法を変更します。

    Args:
        core_mode_ref: コアへの参照。

    Returns:
        定義キー。
    """
    # Split the core ref into "components"; generic origins and arguments are each separate components
    core_ref, mode = core_mode_ref
    components = re.split(r'([\][,])', core_ref)
    # Remove IDs from each component
    components = [x.rsplit(':', 1)[0] for x in components]
    core_ref_no_id = ''.join(components)
    # Remove everything before the last period from each "component"
    components = [re.sub(r'(?:[^.[\]]+\.)+((?:[^.[\]]+))', r'\1', x) for x in components]
    short_ref = ''.join(components)

    mode_title = _MODE_TITLE_MAPPING[mode]

    # It is important that the generated defs_ref values be such that at least one choice will not
    # be generated for any other core_ref. Currently, this should be the case because we include
    # the id of the source type in the core_ref
    name = DefsRef(self.normalize_name(short_ref))
    name_mode = DefsRef(self.normalize_name(short_ref) + f'-{mode_title}')
    module_qualname = DefsRef(self.normalize_name(core_ref_no_id))
    module_qualname_mode = DefsRef(f'{module_qualname}-{mode_title}')
    module_qualname_id = DefsRef(self.normalize_name(core_ref))
    occurrence_index = self._collision_index.get(module_qualname_id)
    if occurrence_index is None:
        self._collision_counter[module_qualname] += 1
        occurrence_index = self._collision_index[module_qualname_id] = self._collision_counter[module_qualname]

    module_qualname_occurrence = DefsRef(f'{module_qualname}__{occurrence_index}')
    module_qualname_occurrence_mode = DefsRef(f'{module_qualname_mode}__{occurrence_index}')

    self._prioritized_defsref_choices[module_qualname_occurrence_mode] = [
        name,
        name_mode,
        module_qualname,
        module_qualname_mode,
        module_qualname_occurrence,
        module_qualname_occurrence_mode,
    ]

    return module_qualname_occurrence_mode

get_cache_defs_ref_schema

get_cache_defs_ref_schema(
    core_ref: CoreRef,
) -> tuple[DefsRef, JsonSchemaValue]

このメソッドは、get_defs_refメソッドをキャッシュ・ルックアップ/ポピュレーション・ロジックでラップし、生成されたdefs_refと、適切な定義を参照するJSONスキーマの両方を返します。

Parameters:

Name Type Description Default
core_ref CoreRef

定義リファレンスを取得するためのコアリファレンス。

required

Returns:

Type Description
tuple[DefsRef, JsonSchemaValue]

定義参照と、それを参照するJSONスキーマのタプル。

Source code in pydantic/json_schema.py
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
def get_cache_defs_ref_schema(self, core_ref: CoreRef) -> tuple[DefsRef, JsonSchemaValue]:
    """このメソッドは、get_defs_refメソッドをキャッシュ・ルックアップ/ポピュレーション・ロジックでラップし、生成されたdefs_refと、適切な定義を参照するJSONスキーマの両方を返します。

    Args:
        core_ref: 定義リファレンスを取得するためのコアリファレンス。

    Returns:
        定義参照と、それを参照するJSONスキーマのタプル。
    """
    core_mode_ref = (core_ref, self.mode)
    maybe_defs_ref = self.core_to_defs_refs.get(core_mode_ref)
    if maybe_defs_ref is not None:
        json_ref = self.core_to_json_refs[core_mode_ref]
        return maybe_defs_ref, {'$ref': json_ref}

    defs_ref = self.get_defs_ref(core_mode_ref)

    # populate the ref translation mappings
    self.core_to_defs_refs[core_mode_ref] = defs_ref
    self.defs_to_core_refs[defs_ref] = core_mode_ref

    json_ref = JsonRef(self.ref_template.format(model=defs_ref))
    self.core_to_json_refs[core_mode_ref] = json_ref
    self.json_to_defs_refs[json_ref] = defs_ref
    ref_json_schema = {'$ref': json_ref}
    return defs_ref, ref_json_schema

handle_ref_overrides

handle_ref_overrides(
    json_schema: JsonSchemaValue,
) -> JsonSchemaValue

最上位の$refを持つスキーマが兄弟キーを持つことは無効です。

During our own schema generation, we treat sibling keys as overrides to the referenced schema, but this is not how the official JSON schema spec works. 自身のスキーマ生成では、兄弟キーを参照されるスキーマに対するオーバーライドとして扱いますが、これは公式のJSONスキーマ仕様の動作方法ではありません。

このため、まず、参照されるスキーマと重複する兄弟キーを削除し、残っている場合は、最上位の'$ref'からスキーマを変換し、allOfを使用して$refを最上位から移動します。 (この動作については、https://swagger.io/docs/specification/using-ref/の下部を参照してください)。

Source code in pydantic/json_schema.py
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
def handle_ref_overrides(self, json_schema: JsonSchemaValue) -> JsonSchemaValue:
    """最上位の$refを持つスキーマが兄弟キーを持つことは無効です。

    During our own schema generation, we treat sibling keys as overrides to the referenced schema, but this is not how the official JSON schema spec works.
    自身のスキーマ生成では、兄弟キーを参照されるスキーマに対するオーバーライドとして扱いますが、これは公式のJSONスキーマ仕様の動作方法ではありません。

    このため、まず、参照されるスキーマと重複する兄弟キーを削除し、残っている場合は、最上位の'$ref'からスキーマを変換し、allOfを使用して$refを最上位から移動します。
    (この動作については、https://swagger.io/docs/specification/using-ref/の下部を参照してください)。
    """
    if '$ref' in json_schema:
        # prevent modifications to the input; this copy may be safe to drop if there is significant overhead
        json_schema = json_schema.copy()

        referenced_json_schema = self.get_schema_from_definitions(JsonRef(json_schema['$ref']))
        if referenced_json_schema is None:
            # This can happen when building schemas for models with not-yet-defined references.
            # It may be a good idea to do a recursive pass at the end of the generation to remove
            # any redundant override keys.
            if len(json_schema) > 1:
                # Make it an allOf to at least resolve the sibling keys issue
                json_schema = json_schema.copy()
                json_schema.setdefault('allOf', [])
                json_schema['allOf'].append({'$ref': json_schema['$ref']})
                del json_schema['$ref']

            return json_schema
        for k, v in list(json_schema.items()):
            if k == '$ref':
                continue
            if k in referenced_json_schema and referenced_json_schema[k] == v:
                del json_schema[k]  # redundant key
        if len(json_schema) > 1:
            # There is a remaining "override" key, so we need to move $ref out of the top level
            json_ref = JsonRef(json_schema['$ref'])
            del json_schema['$ref']
            assert 'allOf' not in json_schema  # this should never happen, but just in case
            json_schema['allOf'] = [{'$ref': json_ref}]

    return json_schema

encode_default

encode_default(dft: Any) -> Any

デフォルト値をJSONシリアル化可能な値にエンコードします。

これは、生成されたJSONスキーマのフィールドのデフォルト値をエンコードするために使用されます。

Parameters:

Name Type Description Default
dft Any

エンコードするデフォルト値。

required

Returns:

Type Description
Any

エンコードされたデフォルト値。

Source code in pydantic/json_schema.py
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
def encode_default(self, dft: Any) -> Any:
    """デフォルト値をJSONシリアル化可能な値にエンコードします。

    これは、生成されたJSONスキーマのフィールドのデフォルト値をエンコードするために使用されます。

    Args:
        dft: エンコードするデフォルト値。

    Returns:
        エンコードされたデフォルト値。
    """
    from .type_adapter import TypeAdapter, _type_has_config

    config = self._config
    try:
        default = (
            dft
            if _type_has_config(type(dft))
            else TypeAdapter(type(dft), config=config.config_dict).dump_python(dft, mode='json')
        )
    except PydanticSchemaGenerationError:
        raise pydantic_core.PydanticSerializationError(f'Unable to encode default value {dft}')

    return pydantic_core.to_jsonable_python(
        default,
        timedelta_mode=config.ser_json_timedelta,
        bytes_mode=config.ser_json_bytes,
    )

update_with_validations

update_with_validations(
    json_schema: JsonSchemaValue,
    core_schema: CoreSchema,
    mapping: dict[str, str],
) -> None

提供されたマッピングを使用してcore_schema内のキーをJSONスキーマの適切なキーに変換し、core_schemaで指定された対応する検証でjson_schemaを更新します。

Parameters:

Name Type Description Default
json_schema JsonSchemaValue

更新するJSONスキーマ。

required
core_schema CoreSchema

検証を取得するコア・スキーマ。

required
mapping dict[str, str]

core_schema属性名から対応するJSONスキーマ属性名へのマッピングです。

required
Source code in pydantic/json_schema.py
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
def update_with_validations(
    self, json_schema: JsonSchemaValue, core_schema: CoreSchema, mapping: dict[str, str]
) -> None:
    """提供されたマッピングを使用してcore_schema内のキーをJSONスキーマの適切なキーに変換し、core_schemaで指定された対応する検証でjson_schemaを更新します。

    Args:
        json_schema: 更新するJSONスキーマ。
        core_schema: 検証を取得するコア・スキーマ。
        mapping: core_schema属性名から対応するJSONスキーマ属性名へのマッピングです。
    """
    for core_key, json_schema_key in mapping.items():
        if core_key in core_schema:
            json_schema[json_schema_key] = core_schema[core_key]

get_json_ref_counts

get_json_ref_counts(
    json_schema: JsonSchemaValue,
) -> dict[JsonRef, int]

json_schema内の任意の場所にあるキー'$ref'に対応するすべての値を取得します。

Source code in pydantic/json_schema.py
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
def get_json_ref_counts(self, json_schema: JsonSchemaValue) -> dict[JsonRef, int]:
    """json_schema内の任意の場所にあるキー'$ref'に対応するすべての値を取得します。"""
    json_refs: dict[JsonRef, int] = Counter()

    def _add_json_refs(schema: Any) -> None:
        if isinstance(schema, dict):
            if '$ref' in schema:
                json_ref = JsonRef(schema['$ref'])
                if not isinstance(json_ref, str):
                    return  # in this case, '$ref' might have been the name of a property
                already_visited = json_ref in json_refs
                json_refs[json_ref] += 1
                if already_visited:
                    return  # prevent recursion on a definition that was already visited
                defs_ref = self.json_to_defs_refs[json_ref]
                if defs_ref in self._core_defs_invalid_for_json_schema:
                    raise self._core_defs_invalid_for_json_schema[defs_ref]
                _add_json_refs(self.definitions[defs_ref])

            for v in schema.values():
                _add_json_refs(v)
        elif isinstance(schema, list):
            for v in schema:
                _add_json_refs(v)

    _add_json_refs(json_schema)
    return json_refs

emit_warning

emit_warning(
    kind: JsonSchemaWarningKind, detail: str
) -> None

このメソッドは、warning_messageメソッドでの処理に基づいて、単にPydantictJsonSchemaWarningsを生成します。

Source code in pydantic/json_schema.py
2145
2146
2147
2148
2149
def emit_warning(self, kind: JsonSchemaWarningKind, detail: str) -> None:
    """このメソッドは、`warning_message`メソッドでの処理に基づいて、単にPydantictJsonSchemaWarningsを生成します。"""
    message = self.render_warning_message(kind, detail)
    if message is not None:
        warnings.warn(message, PydanticJsonSchemaWarning)

render_warning_message

render_warning_message(
    kind: JsonSchemaWarningKind, detail: str
) -> str | None

このメソッドは、必要に応じて警告を無視し、警告メッセージをフォーマットします。

GenerateJsonSchemaのサブクラスのignored_warning_kindの値をオーバーライドして、生成される警告を変更することができます。 より詳細な制御が必要な場合は、このメソッドをオーバーライドできます。 警告を表示したくない場合は、Noneを返してください。

Parameters:

Name Type Description Default
kind JsonSchemaWarningKind

表示する警告の種類。次のいずれかになります。

  • 'skipped-choice': 有効な選択肢がないため、選択肢フィールドがスキップされました。
  • 'non-serializable-default': JSONシリアル化できなかったため、デフォルト値がスキップされました。
required
detail str

警告に関する追加の詳細を含む文字列。

required

Returns:

Type Description
str | None

書式設定された警告メッセージ。警告を表示しない場合はNone

Source code in pydantic/json_schema.py
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
def render_warning_message(self, kind: JsonSchemaWarningKind, detail: str) -> str | None:
    """このメソッドは、必要に応じて警告を無視し、警告メッセージをフォーマットします。

    GenerateJsonSchemaのサブクラスの`ignored_warning_kind`の値をオーバーライドして、生成される警告を変更することができます。
    より詳細な制御が必要な場合は、このメソッドをオーバーライドできます。
    警告を表示したくない場合は、Noneを返してください。

    Args:
        kind: 表示する警告の種類。次のいずれかになります。

            - 'skipped-choice': 有効な選択肢がないため、選択肢フィールドがスキップされました。
            - 'non-serializable-default': JSONシリアル化できなかったため、デフォルト値がスキップされました。

        detail:警告に関する追加の詳細を含む文字列。

    Returns:
        書式設定された警告メッセージ。警告を表示しない場合は`None`。
    """
    if kind in self.ignored_warning_kinds:
        return None
    return f'{detail} [{kind}]'

WithJsonSchema dataclass

WithJsonSchema(
    json_schema: JsonSchemaValue | None,
    mode: (
        Literal["validation", "serialization"] | None
    ) = None,
)

Usage Documentation

WithJsonSchema annotation

これをフィールドのアノテーションとして追加し、そのフィールドに対して生成される(ベース)JSONスキーマをオーバーライドします。 これにより、pydantic.json_schema.GenerateJsonSchemaのカスタムサブクラスを作成しなくても、CallableなどのJSONスキーマの生成時にエラーが発生する型や、is-instanceコアスキーマを持つ型に対してJSONスキーマを設定する方法が提供される。 通常行われるスキーマへの変更(モデルフィールドのタイトルの設定など)は が実行されます。

modeが設定されている場合、これはそのスキーマ生成モードにのみ適用され、検証とシリアライゼーションのために異なるjsonスキーマを設定できます。

Examples dataclass

Examples(
    examples: dict[str, Any],
    mode: (
        Literal["validation", "serialization"] | None
    ) = None,
)

JSONスキーマに例を追加します。

例は、例の名前(文字列)から例の値(任意の有効なJSON)へのマップである必要があります。

modeが設定されている場合、これはそのスキーマ生成モードにのみ適用され、検証とシリアライゼーションのために別の例を追加できます。

SkipJsonSchema dataclass

SkipJsonSchema()

Usage Documentation

SkipJsonSchema annotation

これをアノテーションとしてフィールドに追加すると、そのフィールドのJSONスキーマの生成がスキップされます。

Example
from typing import Union

from pydantic import BaseModel
from pydantic.json_schema import SkipJsonSchema

from pprint import pprint


class Model(BaseModel):
    a: Union[int, None] = None  # (1)!
    b: Union[int, SkipJsonSchema[None]] = None  # (2)!
    c: SkipJsonSchema[Union[int, None]] = None  # (3)!


pprint(Model.model_json_schema())
'''
{
    'properties': {
        'a': {
            'anyOf': [
                {'type': 'integer'},
                {'type': 'null'}
            ],
            'default': None,
            'title': 'A'
        },
        'b': {
            'default': None,
            'title': 'B',
            'type': 'integer'
        }
    },
    'title': 'Model',
    'type': 'object'
}
'''
  1. integer型とnull型はどちらもaのスキーマに含まれています。
  2. integer型は、bのスキーマに含まれる唯一の型です。
  3. cフィールド全体がスキーマから省略されます。

update_json_schema

update_json_schema(
    schema: JsonSchemaValue, updates: dict[str, Any]
) -> JsonSchemaValue

更新の辞書を提供して、JSONスキーマをインプレースで更新します。

この関数は、指定されたキーと値のペアをスキーマに設定し、更新されたスキーマを返します。

Parameters:

Name Type Description Default
schema JsonSchemaValue

更新するJSONスキーマ。

required
updates dict[str, Any]

スキーマに設定するキーと値のペアのディクショナリ。

required

Returns:

Type Description
JsonSchemaValue

更新されたJSONスキーマ。

Source code in pydantic/json_schema.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
@deprecated(
    '`update_json_schema` is deprecated, use a simple `my_dict.update(update_dict)` call instead.',
    category=None,
)
def update_json_schema(schema: JsonSchemaValue, updates: dict[str, Any]) -> JsonSchemaValue:
    """更新の辞書を提供して、JSONスキーマをインプレースで更新します。

    この関数は、指定されたキーと値のペアをスキーマに設定し、更新されたスキーマを返します。

    Args:
        schema: 更新するJSONスキーマ。
        updates: スキーマに設定するキーと値のペアのディクショナリ。

    Returns:
        更新されたJSONスキーマ。
    """
    schema.update(updates)
    return schema

model_json_schema

model_json_schema(
    cls: type[BaseModel] | type[PydanticDataclass],
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[
        GenerateJsonSchema
    ] = GenerateJsonSchema,
    mode: JsonSchemaMode = "validation",
) -> dict[str, Any]

モデルのJSONスキーマを生成するユーティリティ関数。

Parameters:

Name Type Description Default
cls type[BaseModel] | type[PydanticDataclass]

JSONスキーマを生成するためのモデル・クラスです。

required
by_alias bool

True(デフォルト)の場合、フィールドはエイリアスに従ってシリアライズされます。Falseの場合、フィールドは属性名に従ってシリアライズされます。

True
ref_template str

JSONスキーマ参照の生成に使用するテンプレートです。

DEFAULT_REF_TEMPLATE
schema_generator type[GenerateJsonSchema]

JSONスキーマの生成に使用するクラス。

GenerateJsonSchema
mode JsonSchemaMode

JSONスキーマの生成に使用するモード。次のいずれかになります。 - 'validation':データを検証するためのJSONスキーマを生成します。 - 'serialization':データをシリアライズするためのJSONスキーマを生成します。

'validation'

Returns:

Type Description
dict[str, Any]

生成されたJSONスキーマ。

Source code in pydantic/json_schema.py
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
def model_json_schema(
    cls: type[BaseModel] | type[PydanticDataclass],
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
) -> dict[str, Any]:
    """モデルのJSONスキーマを生成するユーティリティ関数。

    Args:
        cls: JSONスキーマを生成するためのモデル・クラスです。
        by_alias: `True`(デフォルト)の場合、フィールドはエイリアスに従ってシリアライズされます。`False`の場合、フィールドは属性名に従ってシリアライズされます。
        ref_template: JSONスキーマ参照の生成に使用するテンプレートです。
        schema_generator: JSONスキーマの生成に使用するクラス。
        mode: JSONスキーマの生成に使用するモード。次のいずれかになります。
            - 'validation':データを検証するためのJSONスキーマを生成します。
            - 'serialization':データをシリアライズするためのJSONスキーマを生成します。

    Returns:
        生成されたJSONスキーマ。
    """
    from .main import BaseModel

    schema_generator_instance = schema_generator(by_alias=by_alias, ref_template=ref_template)

    if isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema):
        cls.__pydantic_core_schema__.rebuild()

    if cls is BaseModel:
        raise AttributeError('model_json_schema() must be called on a subclass of BaseModel, not BaseModel itself.')

    assert not isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema), 'this is a bug! please report it'
    return schema_generator_instance.generate(cls.__pydantic_core_schema__, mode=mode)

models_json_schema

models_json_schema(
    models: Sequence[
        tuple[
            type[BaseModel] | type[PydanticDataclass],
            JsonSchemaMode,
        ]
    ],
    *,
    by_alias: bool = True,
    title: str | None = None,
    description: str | None = None,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[
        GenerateJsonSchema
    ] = GenerateJsonSchema
) -> tuple[
    dict[
        tuple[
            type[BaseModel] | type[PydanticDataclass],
            JsonSchemaMode,
        ],
        JsonSchemaValue,
    ],
    JsonSchemaValue,
]

複数のモデルのJSONスキーマを生成するユーティリティ関数。

Parameters:

Name Type Description Default
by_alias bool

生成されたJSONスキーマでフィールドのエイリアスをキーとして使用するかどうか。

True
title str | None

生成されたJSONスキーマのタイトル。

None
description str | None

生成されたJSONスキーマの説明。

None
ref_template str

JSONスキーマ参照の生成に使用する参照テンプレートです。

DEFAULT_REF_TEMPLATE
schema_generator type[GenerateJsonSchema]

JSONスキーマの生成に使用するスキーマ・ジェネレーターです。

GenerateJsonSchema

Returns:

Name Type Description
次の条件を満たすタプル tuple[dict[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode], JsonSchemaValue], JsonSchemaValue]
  • 最初の要素は、JSONスキーマ・キー・タイプとJSONモードのタプルをキーとし、その入力ペアに対応するJSONスキーマを値とする辞書です (これらのスキーマは、2番目に返された要素で定義されている定義へのJsonRef参照を持つ場合があります)。
  • 2番目の要素は、最初に返された要素で参照されるすべての定義と、オプションのtitleおよびdescriptionキーを含むJSONスキーマです。
Source code in pydantic/json_schema.py
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
def models_json_schema(
    models: Sequence[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode]],
    *,
    by_alias: bool = True,
    title: str | None = None,
    description: str | None = None,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
) -> tuple[dict[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode], JsonSchemaValue], JsonSchemaValue]:
    """複数のモデルのJSONスキーマを生成するユーティリティ関数。

    Args:
        by_alias: 生成されたJSONスキーマでフィールドのエイリアスをキーとして使用するかどうか。
        title: 生成されたJSONスキーマのタイトル。
        description: 生成されたJSONスキーマの説明。
        ref_template: JSONスキーマ参照の生成に使用する参照テンプレートです。
        schema_generator: JSONスキーマの生成に使用するスキーマ・ジェネレーターです。

    Returns:
        次の条件を満たすタプル:
            - 最初の要素は、JSONスキーマ・キー・タイプとJSONモードのタプルをキーとし、その入力ペアに対応するJSONスキーマを値とする辞書です
            (これらのスキーマは、2番目に返された要素で定義されている定義へのJsonRef参照を持つ場合があります)。
            - 2番目の要素は、最初に返された要素で参照されるすべての定義と、オプションのtitleおよびdescriptionキーを含むJSONスキーマです。
    """
    for cls, _ in models:
        if isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema):
            cls.__pydantic_core_schema__.rebuild()

    instance = schema_generator(by_alias=by_alias, ref_template=ref_template)
    inputs: list[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode, CoreSchema]] = [
        (m, mode, m.__pydantic_core_schema__) for m, mode in models
    ]
    json_schemas_map, definitions = instance.generate_definitions(inputs)

    json_schema: dict[str, Any] = {}
    if definitions:
        json_schema['$defs'] = definitions
    if title:
        json_schema['title'] = title
    if description:
        json_schema['description'] = description

    return json_schemas_map, json_schema