スキーマの検証¶
基本原則¶
使用する特定のスキーマの下でインスタンスを検証する最も簡単な方法は、validate() 関数を検証する事です。
- jsonschema.validate(instance, schema, cls=None, *args, **kwargs)¶
指定されたスキーマでインスタンスを検証します。
>>> validate([2, 3, 4], {"maxItems" : 2}) Traceback (most recent call last): ... ValidationError: [2, 3, 4] is too long
validate() will first verify that the provided schema is itself valid, since not doing so can lead to less obvious error messages and fail in less obvious or consistent ways. If you know you have a valid schema already or don’t care, you might prefer using the validate() method directly on a specific validator (e.g. Draft4Validator.validate()).
パラメタ: - instance – インスタンスを検証
- schema – スキーマを検証
- cls – an IValidator class that will be used to validate the instance.
If the cls argument is not provided, two things will happen in accordance with the specification. First, if the schema has a $schema property containing a known meta-schema [1] then the proper validator will be used. The specification recommends that all schemas contain $schema properties for this reason. If no $schema property is found, the default validator class is Draft4Validator.
その他位置引数とキーワード引数は、’cls ‘ をインスタンス化するとき渡されます。
Raises: インスタンスが無効であった場合 ValidationError です。
スキーマ自身が無効であった場合 SchemaError です。
脚注
[1] known by a validator registered with validates()
| [2] | For information on creating JSON schemas to validate your data, there is a good introduction to JSON Schema fundamentals underway at Understanding JSON Schema |
バリデータインターフェース¶
jsonschema (非公式な)インターフェースを定義しています。全てのバリデータはこれに従う必要があります。
- class jsonschema.IValidator(schema, types=(), resolver=None, format_checker=None)¶
パラメタ: - schema (dict) – the schema that the validator will validate with. It is assumed to be valid, and providing an invalid schema can lead to undefined behavior. See IValidator.check_schema() to validate a schema first.
- types (dict or iterable of 2-tuples) – Override or extend the list of known types when validating the type property. Should map strings (type names) to class objects that will be checked via isinstance(). See その他の種類の検証 for details.
- resolver – $ref プロパティ (JSON リファレンス) を解決すろために使われている RefResolver のインスタンスです。提供されていない場合は1つ作成されます。
- format_checker – an instance of FormatChecker whose conforms() method will be called to check and see if instances conform to each format property present in the schema. If unprovided, no validation will be done for format.
- META_SCHEMA¶
バリデーターのメタ ・ スキーマ (特定のバージョンで有効なスキーマを記述するスキーマ) を表すオブジェクト。
- VALIDATORS¶
A mapping of validators (strs) to functions that validate the validator property with that name. For more information see 拡張バリデーターを作成します.
- schema¶
バリデータを初期化するときに渡されたスキーマです。
- classmethod check_schema(schema)¶
バリデータの META_SCHEMA に対して与えられたスキーマをバリデーションします。
Raises: スキーマが無効であった場合 SchemaError です。
- is_type(instance, type)¶
与えられた(JSON Schema)型のインスタンスかをチェックします。
戻り値の型: bool Raises: type が未知の型だったら UnknownType です。
- is_valid(instance)¶
インスタンスが現在の schema 下で有効なかどうか確認
戻り値の型: bool >>> schema = {"maxItems" : 2} >>> Draft3Validator(schema).is_valid([2, 3, 4]) False
- iter_errors(instance)¶
特定のインスタンスの検証エラーを遅延してyieldします。
戻り値の型: ValidationError のイテレータ
>>> schema = { ... "type" : "array", ... "items" : {"enum" : [1, 2, 3]}, ... "maxItems" : 2, ... } >>> v = Draft3Validator(schema) >>> for error in sorted(v.iter_errors([2, 3, 4]), key=str): ... print(error.message) 4 is not one of [1, 2, 3] [2, 3, 4] is too long
- validate(instance)¶
インスタンスが現在の schema 下で有効なかどうか確認
Raises: インスタンスが無効であった場合 ValidationError です。
>>> schema = {"maxItems" : 2} >>> Draft3Validator(schema).validate([2, 3, 4]) Traceback (most recent call last): ... ValidationError: [2, 3, 4] is too long
All of the versioned validators that are included with jsonschema adhere to the interface, and implementors of validators that extend or complement the ones included should adhere to it as well. For more information see 拡張バリデーターを作成します.
その他の種類の検証¶
Occasionally it can be useful to provide additional or alternate types when validating the JSON Schema’s type property. Validators allow this by taking a types argument on construction that specifies additional types, or which can be used to specify a different set of Python types to map to a given JSON type.
jsonschema tries to strike a balance between performance in the common case and generality. For instance, JSON Schema defines a number type, which can be validated with a schema such as {"type" : "number"}. By default, this will accept instances of Python numbers.Number. This includes in particular ints and floats, along with decimal.Decimal objects, complex numbers etc. For integer and object, however, rather than checking for numbers.Integral and collections.abc.Mapping, jsonschema simply checks for int and dict, since the more general instance checks can introduce significant slowdown, especially given how common validating these types are.
If you do want the generality, or just want to add a few specific additional types as being acceptible for a validator, IValidators have a types argument that can be used to provide additional or new types.
class MyInteger(object):
...
Draft3Validator(
schema={"type" : "number"},
types={"number" : (numbers.Number, MyInteger)},
)
The list of default Python types for each JSON type is available on each validator in the IValidator.DEFAULT_TYPES attribute. Note that you need to specify all types to match if you override one of the existing JSON types, so you may want to access the set of default types when specifying your additional type.
バージョン管理されたバリデータ¶
jsonschema ships with validators for various versions of the JSON Schema specification. For details on the methods and attributes that each validator provides see the IValidator interface, which each validator implements.
- class jsonschema.Draft3Validator(schema, types=(), resolver=None, format_checker=None)¶
- class jsonschema.Draft4Validator(schema, types=(), resolver=None, format_checker=None)¶
例えば、 あなたが作成したドラフト4 メタスキーマのスキーマをバリデートしたいなら、このようにします。
from jsonschema import Draft4Validator
schema = {
"$schema": "http://json-schema.org/schema#"
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "string"},
}
"required": ["email"],
}
Draft4Validator.check_schema(schema)
検証フォーマット¶
JSON Schema defines the format property which can be used to check if primitive types (strings, numbers, booleans) conform to well-defined formats. By default, no validation is enforced, but optionally, validation can be enabled by hooking in a format-checking object into an IValidator.
>>> validate("localhost", {"format" : "hostname"})
>>> validate(
... "-12", {"format" : "hostname"}, format_checker=FormatChecker(),
... )
Traceback (most recent call last):
...
ValidationError: "-12" is not a "hostname"
- class jsonschema.FormatChecker(formats=None)¶
フォーマットプロパティチェッカー
JSON Schema does not mandate that the format property actually do any validation. If validation is desired however, instances of this class can be hooked into validators to enable format validation.
FormatChecker objects always return True when asked about formats that they do not know how to validate.
To check a custom format using a function that takes an instance and returns a bool, use the FormatChecker.checks() or FormatChecker.cls_checks() decorators.
パラメタ: formats (iterable) – 検証で知られているフォーマット。この引数は、形式が検証中に使用制限を使用できます。 - checkers¶
A mapping of currently known formats to tuple of functions that validate them and errors that should be caught. New checkers can be added and removed either per-instance or globally for all checkers using the FormatChecker.checks() or FormatChecker.cls_checks() decorators respectively.
- classmethod cls_checks(format, raises=())¶
新しいフォーマットとしてグローバルに検証されるデコレーションされた関数を保存します。
この関数が呼ばれたあとインスタンスが生成されて、付属のチェッカーをピックアップします。
パラメタ: - format (str) – デコレーションされた関数がチェックするフォーマット
- raises (Exception) – the exception(s) raised by the decorated function when an invalid instance is found. The exception object will be accessible as the ValidationError.cause attribute of the resulting validation error.
- check(instance, format)¶
インスタンスが与えられたフォーマットに準拠しているかどうかをチェックします。
パラメタ: - instance – インスタンスをチェックするには
- format (str) – インスタンスの形式に従う必要があります。
Type: 任意のプリミティブ型 (str, number, bool)
Raises: インスタンスがフォーマットに準拠していない場合 FormatError です。
- checks(format, raises=())¶
新しいフォマットとして検証するデコレーションされた関数を保存します。
パラメタ: - format (str) – デコレーションされた関数がチェックするフォーマット
- raises (Exception) – the exception(s) raised by the decorated function when an invalid instance is found. The exception object will be accessible as the ValidationError.cause attribute of the resulting validation error.
There are a number of default checkers that FormatCheckers know how to validate. Their names can be viewed by inspecting the FormatChecker.checkers attribute. Certain checkers will only be available if an appropriate package is available for use. The available checkers, along with their requirement (if any,) are listed below.
チェッカー |
ノート |
|---|---|
ホスト名 |
|
| ipv4 | |
| ipv6 | OSに socket.inet_pton() 関数がある事が必要です |
Eメール |
|
URI |
rfc3987 が必要です |
日時 |
requires strict-rfc3339 [2] |
日付 |
|
時間 |
|
正規表現 |
|
色 |
webcolors が必要です |
| [3] | For backwards compatibility, isodate is also supported, but it will allow any ISO 8601 date-time, not just RFC 3339 as mandated by the JSON Schema specification. |