# JSON 结构

¥JSON Schema

简单来说,JSON Schema 是一个带有校验关键字的对象。

¥In a simple way, JSON Schema is an object with validation keywords.

关键字及其值定义数据应满足哪些规则才有效。

¥The keywords and their values define what rules the data should satisfy to be valid.

# JSON 结构版本

¥JSON Schema versions

# 草案 07

¥draft-07

default

此版本作为默认导出提供:

¥This version is provided as default export:

Draft-07 具有更好的性能

除非你需要更高版本的新功能,否则你将使用此草案生成更高效的代码。

¥Unless you need the new features of later versions, you would have more efficient generated code with this draft.

# 草案 2019-09

¥draft-2019-09

NEW

Ajv 支持 JSON Schema 草案 2019-09 的所有新关键字:

¥Ajv supports all new keywords of JSON Schema draft-2019-09:

要使用 Draft-2019-09 结构,你需要导入不同的 Ajv 类:

¥To use draft-2019-09 schemas you need to import a different Ajv class:

你也可以在此 Ajv 实例中使用 Draft-07 结构,draft-2019-09 向后兼容。如果你的结构使用 $schema 关键字,则需要将 Draft-07 元结构添加到 Ajv 实例:

¥You can use draft-07 schemas with this Ajv instance as well, draft-2019-09 is backwards compatible. If your schemas use $schema keyword, you need to add draft-07 meta-schema to Ajv instance:

# 草案 2020-12

¥draft-2020-12

BREAKING

Draft-2020-12 不向后兼容

你不能在同一 Ajv 实例中使用草案 2020-12 和以前的 JSON 结构版本。

¥You cannot use draft-2020-12 and previous JSON Schema versions in the same Ajv instance.

Ajv 支持 JSON Schema Draft-2020-12 的所有关键字:

¥Ajv supports all keywords of JSON Schema draft-2020-12:

  • prefixItems 替换了 items 关键字的数组形式

    ¥prefixItems that replaced array form of items keyword

  • 更改了 items 关键字,该关键字结合了项目和附加项目的部分功能

    ¥changed items keyword that combined parts of functionality of items and additionalItems

  • $dynamicAnchor/$dynamicRef

要使用 Draft-2020-12 结构,你需要导入不同的 Ajv 类:

¥To use draft-2020-12 schemas you need to import a different Ajv class:

# 草案 06

¥draft-06

你可以将 JSON 结构草案 06 结构与 Ajv v7/8 结合使用。如果你的结构使用 $schema 关键字,则需要将 Draft-06 元结构添加到 Ajv 实例。此示例显示如何支持 Draft-06 和 Draft-07 结构:

¥You can use JSON Schema draft-06 schemas with Ajv v7/8. If your schemas use $schema keyword, you need to add draft-06 meta-schema to Ajv instance. This example shows how to support both draft-06 and draft-07 schemas:

# 草案 04

¥draft-04

你可以将 JSON Schema Draft-04 结构与 v8.5.0 中的 Ajv 和附加包 ajv-draft-04 (opens new window) 一起使用(应安装 ajv 和 ajv-draft-04)。

¥You can use JSON Schema draft-04 schemas with Ajv from v8.5.0 and the additional package ajv-draft-04 (opens new window) (both ajv and ajv-draft-04 should be installed).

Ajv 无法组合多个 JSON Schema 版本

你只能将此导入与 JSON Schema Draft-04 一起使用,不能在此 ajv 实例中组合多个 JSON Schema 版本。

¥You can only use this import with JSON Schema draft-04, you cannot combine multiple JSON Schema versions in this ajv instance.

# 开放 API 支持

¥OpenAPI support

Ajv 支持以下附加 开放 API 规范 (opens new window) 关键字:

¥Ajv supports these additional OpenAPI specification (opens new window) keywords:

  • nullable - 避免将 type 关键字与类型数组一起使用。

    ¥nullable - to avoid using type keyword with array of types.

  • discriminator - 优化标记联合的校验和错误报告

    ¥discriminator - to optimize validation and error reporting of tagged unions

# JSON 数据类型

¥JSON data type

# type

type 关键字要求数据属于某种类型(或某些类型)。它的值可以是字符串(允许的类型)或字符串数组(允许的多个类型)。

¥type keyword requires that the data is of certain type (or some of types). Its value can be a string (the allowed type) or an array of strings (multiple allowed types).

类型可以是:numberintegerstringbooleanarrayobjectnull

¥Type can be: number, integer, string, boolean, array, object or null.

示例

¥Examples

  1. schema:{type: "number"}

    valid:11.5

    invalid:"abc""1"[]{}nulltrue

  1. schema:{type: "integer"}

    valid:12

    invalid:"abc""1"1.5[]{}nulltrue

  1. schema:{type: ["number", "string"]}

    valid:11.5"abc""1"

    invalid:[]{}nulltrue

上面的所有示例都是 JSON 结构,仅要求数据属于某种类型才有效。

¥All examples above are JSON Schemas that only require data to be of certain type to be valid.

大多数其他关键字仅适用于特定类型的数据。如果数据类型不同,则关键字不适用,数据将被视为有效。

¥Most other keywords apply only to a particular type of data. If the data is of different type, the keyword will not apply and the data will be considered valid.

在 v7 中,Ajv 引入了 严格类型 结构,该结构要求每当使用适用于特定类型的另一个关键字时都使用 type 关键字来约束类型,从而降低了这些错误的可能性。

¥In v7 Ajv introduced Strict types mode that makes these mistakes less likely by requiring that types are constrained with type keyword whenever another keyword that applies to specific type is used.

# nullable

OpenAPI

除了定义的 type 之外,该关键字还可用于允许 null 值。

¥This keyword can be used to allow null value in addition to the defined type.

Ajv 默认支持,无需额外选项。这两个结构是等效的,但第一个结构更受某些工具支持,并且也与 strictTypes 选项兼容(参见 严格类型

¥Ajv supports it by default, without additional options. These two schemas are equivalent, but the first one is better supported by some tools and is also compatible with strictTypes option (see Strict types)

{
  "type": "string",
  "nullable": true
}

and

{
  "type": ["string", "null"]
}

nullable 不扩展 enum 和 const

如果你使用 enumconst 关键字,"nullable": true 不会扩展允许值列表 - null 值必须显式添加到 enumconst 会失败,除非它是 "const": null

¥If you use enum or const keywords, "nullable": true would not extend the list of allowed values - null value has to be explicitly added to enum (and const would fail, unless it is "const": null)

这与 JSON 类型定义 中定义 nullable 的方式不同,其中 "nullable": true 除了结构定义的任何数据之外还允许 null 值。

¥This is different from how nullable is defined in JSON Type Definition, where "nullable": true allows null value in addition to any data defined by the schema.

# 数字的关键词

¥Keywords for numbers

# maximum / minimumexclusiveMaximum / exclusiveMinimum

¥maximum / minimum and exclusiveMaximum / exclusiveMinimum

关键字 maximum (minimum) 的值应该是一个数字。该值是数据有效的最大(最小)允许值。

¥The value of keyword maximum (minimum) should be a number. This value is the maximum (minimum) allowed value for the data to be valid.

关键字 exclusiveMaximum (exclusiveMinimum) 的值应该是一个数字。该值是数据有效的唯一最大(最小)允许值(等于该关键字值的数据无效)。

¥The value of keyword exclusiveMaximum (exclusiveMinimum) should be a number. This value is the exclusive maximum (minimum) allowed value for the data to be valid (the data equal to this keyword value is invalid).

不支持布尔关键字值

不支持关键字 exclusiveMaximum (exclusiveMinimum) 的布尔值。

¥Boolean values for keywords exclusiveMaximum (exclusiveMinimum) are not supported.

示例

¥Examples

  1. schema:{type: "number", maximum: 5}

    valid:45

    invalid:67

  2. schema:{type: "number", minimum: 5}

    valid:56

    invalid:44.5

  3. schema:{type: "number", exclusiveMinimum: 5}

    valid:67

    invalid:4.55

# multipleOf

关键字的值应该是一个数字。有效的数据应该是关键字值的倍数(即数据除以该值的结果应该是整数)。

¥The value of the keyword should be a number. The data to be valid should be a multiple of the keyword value (i.e. the result of division of the data on the value should be integer).

示例

¥Examples

  1. schema:{type: "number", multipleOf: 5}

    valid:510

    invalid:14

  1. schema:{type: "number", multipleOf: 2.5}

    valid:2.557.5

    invalid:14

# 字符串的关键字

¥Keywords for strings

# maxLength/minLength

关键字的值应该是一个数字。有效数据的长度应满足此规则。Unicode 对被视为单个字符。

¥The value of the keywords should be a number. The data to be valid should have length satisfying this rule. Unicode pairs are counted as a single character.

示例

¥Examples

  1. schema:{type: "string", maxLength: 5}

    valid:"abc""abcde"

    invalid:"abcdef"

  1. schema:{type: "string", minLength: 2}

    valid:"ab""😀😀"

    invalid:"a""😀"

# pattern

关键字的值应该是一个字符串。有效的数据应与关键字值定义的正则表达式匹配。

¥The value of the keyword should be a string. The data to be valid should match the regular expression defined by the keyword value.

Ajv 使用 new RegExp(value, "u") 创建将用于测试数据的正则表达式。

¥Ajv uses new RegExp(value, "u") to create the regular expression that will be used to test data.

示例

¥Example

schema:{type: "string", pattern: "[abc]+"}

valid:"a""abcd""cde"

invalid:"def"""

# format

关键字的值应该是一个字符串。有效的数据应与该名称的格式匹配。

¥The value of the keyword should be a string. The data to be valid should match the format with this name.

Ajv 不包含任何格式,可以使用 ajv-formats (opens new window) 插件添加它们。

¥Ajv does not include any formats, they can be added with ajv-formats (opens new window) plugin.

示例

¥Example

schema:{type: "string", format: "ipv4"}

valid:"192.168.0.1"

invalid:"abc"

# 数组的关键字

¥Keywords for arrays

# maxItems/minItems

关键字的值应该是一个数字。有效的数据数组不应包含比关键字值更多(更少)的项目。

¥The value of the keywords should be a number. The data array to be valid should not have more (less) items than the keyword value.

示例

¥Example

schema:{type: "array", maxItems: 3}

valid:[][1]["1", 2, "3"]

invalid:[1, 2, 3, 4]

# uniqueItems

关键字的值应该是布尔值。如果关键字值为 true,则有效的数据数组应具有唯一的项。

¥The value of the keyword should be a boolean. If the keyword value is true, the data array to be valid should have unique items.

示例

¥Example

schema:{type: "array", uniqueItems: true}

valid:[][1]["1", 2, "3"]

invalid:[1, 2, 1][{a: 1, b: 2}, {b: 2, a: 1}]

# items

# 草案 04、06、07 和 2019-09 中的 items

¥items in draft-04, -06, -07 and -2019-09

JSON 结构草案 2020-12 中的 items 关键字已更改

本节介绍 Draft-2020-12 之前的所有 JSON Schema 版本中的 items 关键字。

¥This section describes items keyword in all JSON Schema versions prior to draft-2020-12.

关键字的值应该是一个结构或结构数组。

¥The value of the keyword should be a schema or an array of schemas.

如果关键字值是结构,则为了使数据数组有效,数组中的每个项目都应该根据结构有效。在这种情况下,additionalItems 关键字将被忽略。

¥If the keyword value is a schema, then for the data array to be valid each item of the array should be valid according to the schema. In this case the additionalItems keyword is ignored.

如果关键字值是数组,则根据具有相同索引的结构,索引小于关键字中的项目数的项目应该是有效的。附加项目是否有效将取决于 additionalItems 关键字。

¥If the keyword value is an array, then items with indices less than the number of items in the keyword should be valid according to the schemas with the same indices. Whether additional items are valid will depend on additionalItems keyword.

示例

¥Examples

  1. schema:{type: "array", items: {type: "integer"}}

    valid:[1,2,3][]

    invalid:[1,"abc"]

  2. schema:

    {
      type: "array",
      items: [{type: "integer"}, {type: "string"}]
    }
    

    valid:[1][1, "abc"][1, "abc", 2][]

    invalid:["abc", 1]["abc"]

示例 2 中的结构默认会记录警告(请参阅 strictTuples 选项),因为它定义了不受约束的元组。要定义恰好包含 2 个元素的元组,请使用 minItemsadditionalItems 关键字(请参阅 additionalItems 中的示例 1)。

¥The schema in example 2 will log warning by default (see strictTuples option), because it defines unconstrained tuple. To define a tuple with exactly 2 elements use minItems and additionalItems keywords (see example 1 in additionalItems).

# 草案 2020-12 中的 items

¥items in draft-2020-12

NEW

JSON 结构草案 2020-12 中的 items 关键字已更改

本节介绍 JSON Draft-2020-12 中的 items 关键字。

¥This section describes items keyword in JSON draft-2020-12.

关键字的值必须是结构。

¥The value of the keyword must be a schema.

为了使数据数组有效:

¥For the data array to be valid:

  • 如果结构中未使用 prefixItems 关键字,则根据 items 中的结构,数组的每一项都必须有效。

    ¥if prefixItems keyword is not used in the schema, then each item of the array must be valid according to the schema in items.

  • 如果结构中使用了 prefixItems 关键字,则索引从 prefixItems 结构的大小开始的每个项目必须根据 items 中的结构有效

    ¥if prefixItems keyword is used in the schema, then each item with the index starting from the size of prefixItems schema must be valid according to the schema in items

示例

¥Examples

  1. schema:{type: "array", items: {type: "integer"}}

    valid:[1,2,3][]

    invalid:[1,"abc"]

  2. schema:

    {
      type: "array",
      prefixItems: [{type: "integer"}, {type: "integer"}],
      minItems: 2
      items: false
    }
    

    valid:[1, 2]

    invalid:[][1][1, 2, 3][1, "abc"](任何错误数量或错误类型)

    ¥invalid: [], [1], [1, 2, 3], [1, "abc"] (any wrong number of items or wrong type)

  3. schema:

    {
      type: "array",
      prefixItems: [{type: "integer"}, {type: "integer"}],
      items: {type: "string"}
    }
    

    valid:[][1, 2][1, 2, "abc"]

    invalid:["abc"][1, 2, 3]

    valid:[1][1, "abc"][1, "abc", 2][]

    invalid:["abc", 1]["abc"]

示例 3 中的结构默认会记录警告(请参阅 strictTuples 选项),因为它定义了不受约束的元组。要定义恰好包含 2 个元素的元组,请使用 minItemsitems 关键字(请参见示例 2)。

¥The schema in example 3 will log warning by default (see strictTuples option), because it defines unconstrained tuple. To define a tuple with exactly 2 elements use minItems and items keywords (see example 2).

# prefixItems

NEW: draft 2020-12

关键字的值必须是结构数组。

¥The value of the keyword must be an array of schemas.

为了使数据数组有效,索引小于该关键字中结构数量的项目必须根据具有相同索引的结构有效。附加项目是否有效将取决于 items 关键字。

¥For the data array to be valid, the items with indices less than the number of schemas in this keyword must be valid according to the schemas with the same indices. Whether additional items are valid will depend on items keyword.

示例

¥Examples

schema:

{
  type: "array",
  prefixItems: [{type: "integer"}, {type: "string"}]
}

valid:[1][1, "abc"][1, "abc", 2][]

invalid:["abc", 1]["abc"]

示例中的结构默认会记录警告(请参阅 strictTuples 选项),因为它定义了不受约束的元组。要定义恰好包含 2 个元素的元组,请使用 minItemsitems 关键字(请参阅 items 中的示例 2)。

¥The schema in example will log warning by default (see strictTuples option), because it defines unconstrained tuple. To define a tuple with exactly 2 elements use minItems and items keywords (see example 2 in items).

# additionalItems

JSON 结构草案 2020-12 不支持 extraItems

要在 Draft-2020-12 中创建等效架构,请使用关键字 prefixItems 和新的 items 关键字

¥To create and equivalent schema in draft-2020-12 use keywords prefixItems and the new items keyword

关键字的值应该是布尔值或对象。

¥The value of the keyword should be a boolean or an object.

如果 items 关键字不存在或者它是一个对象,则无论其值如何,都应忽略 additionalItems 关键字。默认情况下,Ajv 在这种情况下会抛出异常 - 参见 严格模式

¥If items keyword is not present or it is an object, additionalItems keyword should be ignored regardless of its value. By default Ajv will throw exception in this case - see Strict mode

如果 items 关键字是一个数组,并且数据数组的项数不超过 items 关键字值的长度,则 additionalItems 关键字也会被忽略。

¥If items keyword is an array and data array has not more items than the length of items keyword value, additionalItems keyword is also ignored.

如果数据数组的长度大于 "items" 关键字值的长度,则校验结果取决于 additionalItems 关键字的值:

¥If the length of data array is bigger than the length of "items" keyword value than the result of the validation depends on the value of additionalItems keyword:

  • false:数据无效

    ¥false: data is invalid

  • true:数据有效

    ¥true: data is valid

  • 一个东西:如果所有附加项目(即索引大于或等于 "items" 关键字值长度的项目)根据 "additionalItems" 关键字中的结构有效,则数据有效。

    ¥an object: data is valid if all additional items (i.e. items with indices greater or equal than "items" keyword value length) are valid according to the schema in "additionalItems" keyword.

示例 2-3 中的结构默认记录警告,使用选项 strictTuples: false 允许)

¥The schemas in examples 2-3 log warning by default, use option strictTuples: false to allow)

示例

¥Examples

  1. schema:

    {
      type: "array",
      items: [{type: "integer"}, {type: "integer"}],
      minItems: 2
      additionalItems: false
    }
    

    valid:[1, 2]

    invalid:[][1][1, 2, 3][1, "abc"](任何错误数量或错误类型)

    ¥invalid: [], [1], [1, 2, 3], [1, "abc"] (any wrong number of items or wrong type)

  2. schema:

    {
      type: "array",
      items: [{type: "integer"}, {type: "integer"}],
      additionalItems: true
    }
    

    valid:[][1, 2][1, 2, 3][1, 2, "abc"]

    invalid:["abc"][1, "abc", 3]

  3. schema:

    {
      type: "array",
      items: [{type: "integer"}, {type: "integer"}],
      additionalItems: {type: "string"}
    }
    

    valid:[][1, 2][1, 2, "abc"]

    invalid:["abc"][1, 2, 3]

# contains

关键字的值是一个 JSON Schema。如果该数组包含至少一项根据此结构有效的项目,则该数组有效。

¥The value of the keyword is a JSON Schema. The array is valid if it contains at least one item that is valid according to this schema.

示例

¥Example

schema:{type: "array", contains: {type: "integer"}}

valid:[1][1, "foo"]、任何至少有一个整数的数组

¥valid: [1], [1, "foo"], any array with at least one integer

invalid:[]["foo", "bar"]、任何不带整数的数组

¥invalid: [], ["foo", "bar"], any array without integers

# maxContains/minContains

NEW: draft 2019-09

这些关键字的值应该是整数。

¥The value of these keywords should be an integer.

如果没有 contains 关键字,它们将被忽略(在 ajv 严格模式 中记录错误或引发异常)。

¥Without contains keyword they are ignored (logs error or throws exception in ajv strict mode).

如果数组包含至少 minContains 个项目且不超过 maxContains 个对 contains 关键字中的结构有效的项目,则该数组有效。

¥The array is valid if it contains at least minContains items and no more than maxContains items that are valid against the schema in contains keyword.

示例

¥Example

schema:

{
  type: "array",
  contains: {type: "integer"},
  minContains: 2,
  maxContains: 3
}

valid:[1, 2][1, 2, 3, "foo"]、任何具有 2 或 3 个整数的数组

¥valid: [1, 2], [1, 2, 3, "foo"], any array with 2 or 3 integers

invalid:[][1, "foo"][1, 2, 3, 4],任何少于 2 个或多于 3 个整数的数组

¥invalid: [], [1, "foo"], [1, 2, 3, 4], any array with fewer than 2 or more than 3 integers

# unevaluatedItems

NEW: draft 2019-09

该关键字的值是一个 JSON Schema(可以是布尔值)。

¥The value of this keyword is a JSON Schema (can be a boolean).

此结构将应用于当前结构中的项目(itemsadditionalItemscontains)的其他关键字未评估的所有数组项以及对此数据实例有效的所有子结构。这包括:

¥This schema will be applied to all array items that were not evaluated by other keywords for items (items, additionalItems and contains) in the current schema and all sub-schemas that were valid for this data instance. It includes:

  • allOf$ref 关键字中的所有子结构结构

    ¥all subschemas schemas in allOf and $ref keywords

  • oneOfanyOf 关键字中的有效子结构

    ¥valid sub-schemas in oneOf and anyOf keywords

  • if 关键字中的子结构

    ¥sub-schema in if keyword

  • 根据 if 关键字的校验结果应用 thenelse 关键字中的子结构。

    ¥sub-schemas in then or else keywords that were applied based on the validation result by if keyword.

此关键字应用于某些项目的唯一情况是当 items 关键字值是结构数组并且 additionalItems 不存在(或不应用,以防它出现在某些无效子结构中)。

¥The only scenario when this keyword would be applied to some items is when items keyword value is an array of schemas and additionalItems was not present (or did not apply, in case it was present in some invalid subschema).

一些用户定义的关键字也可以使项目 "evaluated"。

¥Some user-defined keywords can also make items "evaluated".

示例

¥Example

schema:

{
  type: "array",
  items: [
    {type: "number"},
    {type: "number"}
  ],
  unevaluatedItems: false,
  anyOf: [
    {items: [true, true, {type: "number"}]},
    {items: [true, true, {type: "boolean"}]}
  ]
}

valid:[1, 2, 3][1, 2, true]

invalid:

  • [1, 2] - 第三项不存在

    ¥[1, 2] - the third item is not present

  • [1, 2, "3"] - 第三项是 "unevaluated"

    ¥[1, 2, "3"] - the third item is "unevaluated"

有关其他示例,请参阅 tests (opens new window) for unevaluatedItems 关键字。

¥See tests (opens new window) for unevaluatedItems keyword for other examples.

# 对象的关键字

¥Keywords for objects

# maxProperties/minProperties

关键字的值应该是一个数字。有效的数据对象的属性不应多于(少于)关键字值。

¥The value of the keywords should be a number. The data object to be valid should have not more (less) properties than the keyword value.

示例

¥Example

schema:{type: "object", maxProperties: 2 }

valid:{}{a: 1}{a: "1", b: 2}

invalid:{a: 1, b: 2, c: 3}

# required

关键字的值应该是唯一字符串的数组。有效的数据对象应包含名称与关键字值中的元素相同的所有属性。

¥The value of the keyword should be an array of unique strings. The data object to be valid should contain all properties with names equal to the elements in the keyword value.

示例

¥Example

schema:{type: "object", required: ["a", "b"]}

valid:{a: 1, b: 2}{a: 1, b: 2, c: 3}

invalid:{}{a: 1}{c: 3, d: 4}

# properties

关键字的值应该是一个映射,其键等于数据对象属性。映射中的每个值都应该是一个 JSON 结构。为了使数据对象有效,数据对象属性中的相应值应该根据这些结构有效。

¥The value of the keyword should be a map with keys equal to data object properties. Each value in the map should be a JSON Schema. For data object to be valid the corresponding values in data object properties should be valid according to these schemas.

属性不是必需的

properties 关键字不要求其中提到的属性存在于对象中(参见示例)。

¥properties keyword does not require that the properties mentioned in it are present in the object (see examples).

示例

¥Example

schema:

{
  type: "object",
  properties: {
    foo: {type: "string"},
    bar: {
      type: "number",
      minimum: 2
    }
  }
}

valid:{}{foo: "a"}{foo: "a", bar: 2}

invalid:{foo: 1}{foo: "a", bar: 1}

# patternProperties

该关键字的值应该是一个映射,其中键应该是正则表达式,值应该是 JSON 结构。为了使数据对象有效,与正则表达式匹配的数据对象属性中的值应该根据相应的模式有效。

¥The value of this keyword should be a map where keys should be regular expressions and the values should be JSON Schemas. For data object to be valid the values in data object properties that match regular expression(s) should be valid according to the corresponding schema(s).

当数据对象属性中的值与多个正则表达式匹配时,根据所有匹配的正则表达式的所有结构,它应该是有效的。

¥When the value in data object property matches multiple regular expressions it should be valid according to all the schemas for all matched regular expressions.

意外的校验结果

  1. patternProperties 关键字不要求对象中存在与结构匹配的属性(请参阅示例)。

    ¥patternProperties keyword does not require that properties matching patterns are present in the object (see examples).

  2. 默认情况下,Ajv 不允许 patternProperties 中的模式与 properties 关键字中的任何属性名称匹配的模式 - 这会导致意外的校验结果。可以使用选项 allowMatchingProperties 来允许它。见 严格模式

    ¥By default, Ajv does not allow schemas where patterns in patternProperties match any property name in properties keyword - that leads to unexpected validation results. It can be allowed with option allowMatchingProperties. See Strict mode

示例

¥Example

schema:

{
  type: "object",
  patternProperties: {
    "^fo.*$": {type: "string"},
    "^ba.*$": {type: "number"}
  }
}

valid:{}{foo: "a"}{foo: "a", bar: 1}

invalid:{foo: 1}{foo: "a", bar: "b"}

# additionalProperties

关键字的值应该是布尔值或 JSON 结构。

¥The value of the keyword should be either a boolean or a JSON Schema.

如果值为 true,则忽略关键字。

¥If the value is true the keyword is ignored.

如果值为 false,则有效的数据对象不应具有 "附加属性"(即,除了 "properties" 关键字中使用的属性以及与 "patternProperties" 关键字中的结构匹配的属性之外的属性)。

¥If the value is false the data object to be valid should not have "additional properties" (i.e. properties other than those used in "properties" keyword and those that match patterns in "patternProperties" keyword).

如果该值是数据对象有效的结构,则根据该结构,所有 "附加属性" 中的值都应该有效。

¥If the value is a schema for the data object to be valid the values in all "additional properties" should be valid according to this schema.

示例

¥Examples

  1. schema:

    {
      type: "object",
      properties: {
        foo: {type: "number"}
      },
      patternProperties: {
        "^.*r$": {type: "number"}
      },
      additionalProperties: false
    }
    

    valid:{}{foo: 1}{foo: 1, bar: 2}

    invalid:{a: 3}{foo: 1, baz: 3}

  2. schema:

    {
      type: "object",
      properties: {
        foo: {type: "number"}
      },
      patternProperties: {
        "^.*r$": {type: "number"}
      },
      additionalProperties: {type: "string"}
    }
    

    valid:{}{a: "b"}{foo: 1}{foo: 1, bar: 2}{foo: 1, bar: 2, a: "b"}

    invalid:{a: 3}{foo: 1, baz: 3}

  3. schema:

    {
      type: "object",
      properties: {
        foo: {type: "number"}
      },
      additionalProperties: false,
      anyOf: [
        {
          properties: {
            bar: {type: "number"}
          }
        },
        {
          properties: {
            baz: {type: "number"}
          }
        }
      ]
    }
    

    valid:{}{foo: 1}

    invalid:{bar: 2}{baz: 3}{foo: 1, bar: 2}

    ¥invalid: {bar: 2}, {baz: 3}, {foo: 1, bar: 2}, etc.

# dependencies

deprecated in draft 2019-09

该关键字已被弃用。关键字 dependentRequireddependentSchemas 可以提供相同的功能。

¥This keyword is deprecated. The same functionality is available with keywords dependentRequired and dependentSchemas.

关键字的值是一个映射,其键等于数据对象属性。映射中的每个值应该是唯一属性名称的数组("属性依赖" - 请参阅 dependentRequired 关键字)或 JSON 架构("结构依赖" - see dependentSchemas keyword).

¥The value of the keyword is a map with keys equal to data object properties. Each value in the map should be either an array of unique property names ("property dependency" - see dependentRequired keyword) or a JSON Schema ("schema dependency" - see dependentSchemas keyword).

对于属性依赖,如果数据对象包含作为关键字值中的键的属性,则为了有效,数据对象还应该包含属性数组中的所有属性。

¥For property dependency, if the data object contains a property that is a key in the keyword value, then to be valid the data object should also contain all properties from the array of properties.

对于结构依赖,如果数据对象包含作为关键字值中的键的属性,则为了有效,数据对象本身(而不是属性值)应该根据结构有效。

¥For schema dependency, if the data object contains a property that is a key in the keyword value, then to be valid the data object itself (NOT the property value) should be valid according to the schema.

示例

¥Examples

  1. 结构(属性依赖):

    ¥schema (property dependency):

    {
      type: "object",
      dependencies: {
        foo: ["bar", "baz"]
      }
    }
    

    valid:{foo: 1, bar: 2, baz: 3}{}{a: 1}

    invalid:{foo: 1}{foo: 1, bar: 2}{foo: 1, baz: 3}

  2. 结构(结构依赖):

    ¥schema (schema dependency):

    {
      type: "object",
      dependencies: {
        foo: {
          properties: {
            bar: {type: "number"}
          }
        }
      }
    }
    

    valid:{}{foo: 1}{foo: 1, bar: 2}{a: 1}

    invalid:{foo: 1, bar: "a"}

# dependentRequired

NEW: draft 2019-09

该关键字的值应该是一个映射,其键等于数据对象属性。映射中的每个值都应该是唯一属性名称的数组。

¥The value of this keyword should be a map with keys equal to data object properties. Each value in the map should be an array of unique property names.

如果数据对象包含作为关键字值中的键的属性,则为了有效,数据对象还应包含该关键字中相应属性数组中的所有属性。

¥If the data object contains a property that is a key in the keyword value, then to be valid the data object should also contain all properties from the corresponding array of properties in this keyword.

示例

¥Example

schema:

{
  type: "object",
  dependentRequired: {
    foo: ["bar", "baz"]
  }
}

valid:{foo: 1, bar: 2, baz: 3}{}{a: 1}

invalid:{foo: 1}{foo: 1, bar: 2}{foo: 1, baz: 3}

# dependentSchemas

NEW: draft 2019-09

关键字的值应该是一个映射,其键等于数据对象属性。映射中的每个值都应该是一个 JSON 结构。

¥The value of the keyword should be a map with keys equal to data object properties. Each value in the map should be a JSON Schema.

如果数据对象包含作为关键字值中的键的属性,则为了有效,数据对象本身(而不是属性值)应该根据该关键字中的相应结构有效。

¥If the data object contains a property that is a key in the keyword value, then to be valid the data object itself (NOT the property value) should be valid according to the corresponding schema in this keyword.

示例

¥Example

schema:

{
  type: "object",
  dependentSchemas: {
    foo: {
      properties: {
        bar: {type: "number"}
      }
    }
  }
}

valid:{}{foo: 1}{foo: 1, bar: 2}{a: 1}

invalid:{foo: 1, bar: "a"}

# propertyNames

该关键字的值是一个 JSON Schema。

¥The value of this keyword is a JSON Schema.

为了使数据对象有效,该对象中的每个属性名称都应该根据此结构有效。

¥For data object to be valid each property name in this object should be valid according to this schema.

示例

¥Example

结构(需要 ajv-formats (opens new window) 中的 email 格式):

¥schema (requires email format from ajv-formats (opens new window)):

{
  type: "object",
  propertyNames: {
    format: "email"
  }
}

valid:{"foo@bar.com": "any", "bar@bar.com": "any"}

invalid:{foo: "any value"}

# unevaluatedProperties

NEW: draft 2019-09

该关键字的值是一个 JSON Schema(可以是布尔值)。

¥The value of this keyword is a JSON Schema (can be a boolean).

此结构将应用于当前结构以及对此数据实例有效的所有子结构中未由属性(propertiespatternPropertiesadditionalProperties)的其他关键字评估的所有属性。这包括:

¥This schema will be applied to all properties that were not evaluated by other keywords for properties (properties, patternProperties and additionalProperties) in the current schema and all sub-schemas that were valid for this data instance. It includes:

  • allOf$ref 关键字中的所有子结构结构

    ¥all subschemas schemas in allOf and $ref keywords

  • oneOfanyOf 关键字中的有效子结构

    ¥valid sub-schemas in oneOf and anyOf keywords

  • if 关键字中的子结构

    ¥sub-schema in if keyword

  • 根据 if 关键字的校验结果应用 thenelse 关键字中的子结构。

    ¥sub-schemas in then or else keywords that were applied based on the validation result by if keyword.

一些用户定义的关键字也可以使属性 "evaluated"。

¥Some user-defined keywords can also make properties "evaluated".

示例

¥Example

schema:

{
  type: "object",
  required: ["foo"],
  properties: {foo: {type: "number"}},
  unevaluatedProperties: false,
  anyOf: [
    {
      required: ["bar"],
      properties: {bar: {type: "number"}}
    }
    {
      required: ["baz"],
      properties: {baz: {type: "number"}}
    }
  ]
}

valid:{foo: 1, bar: 2}{foo: 1, baz: 2}{foo: 1, bar: 2, baz: 3}

invalid:

  • {foo: 1} - barbaz 均不存在

    ¥{foo: 1} - neither bar nor baz are present

  • {foo: 1, bar: 2, boo: 3} - boo 未评估

    ¥{foo: 1, bar: 2, boo: 3} - boo is unevaluated

  • {foo: 1, bar: 2, baz: "3"} - 对于第二个子结构无效,因此 baz 是 "unevaluated"。

    ¥{foo: 1, bar: 2, baz: "3"} - not valid against the 2nd subschema, so baz is "unevaluated".

有关其他示例,请参阅 tests (opens new window) for unevaluatedProperties 关键字。

¥See tests (opens new window) for unevaluatedProperties keyword for other examples.

# discriminator

NEW: OpenAPI

Ajv 对 discriminator 关键字的支持有限:优化校验、错误处理以及 修改数据oneOf 关键字。

¥Ajv has a limited support for discriminator keyword: to optimize validation, error handling, and modifying data with oneOf keyword.

它的值应该是一个具有 propertyName 属性的对象 - 用于区分联合成员的属性名称。

¥Its value should be an object with a property propertyName - the name of the property used to discriminate between union members.

当使用鉴别器关键字时,仅使用 oneOf 中的一个子结构,由鉴别器属性的值确定。

¥When using discriminator keyword only one subschema in oneOf will be used, determined by the value of discriminator property.

使用选项鉴别器

要使用 discriminator 关键字,你必须将选项 discriminator: true 与 Ajv 构造函数一起使用 - 默认情况下不启用它。

¥To use discriminator keyword you have to use option discriminator: true with Ajv constructor - it is not enabled by default.

示例

¥Example

schema:

{
  type: "object",
  discriminator: {propertyName: "foo"},
  required: ["foo"],
  oneOf: [
    {
      properties: {
        foo: {const: "x"},
        a: {type: "string"},
      },
      required: ["a"],
    },
    {
      properties: {
        foo: {enum: ["y", "z"]},
        b: {type: "string"},
      },
      required: ["b"],
    },
  ],
}

valid:{foo: "x", a: "any"}{foo: "y", b: "any"}{foo: "z", b: "any"}

invalid:

  • {}{foo: 1} - 鉴别器标签必须是字符串

    ¥{}, {foo: 1} - discriminator tag must be string

  • {foo: "bar"} - 鉴别器标记值必须位于 oneOf 子结构中

    ¥{foo: "bar"} - discriminator tag value must be in oneOf subschema

  • {foo: "x", b: "b"}{foo: "y", a: "a"} - 无效对象

    ¥{foo: "x", b: "b"}, {foo: "y", a: "a"} - invalid object

从校验结果来看,discriminator 被定义为无操作(即删除鉴别器不会改变数据的有效性),但如果数据无效,则报告的错误会有所不同。

¥From the perspective of validation result discriminator is defined as no-op (that is, removing discriminator will not change the validity of the data), but errors reported in case of invalid data will be different.

使用 discriminator 关键字有以下要求和限制:

¥There are following requirements and limitations of using discriminator keyword:

  • 不支持鉴别器对象中的 mapping

    ¥mapping in discriminator object is not supported.

  • oneOf 关键字必须出现在同一结构中。

    ¥oneOf keyword must be present in the same schema.

  • 鉴别器属性应为 required,无论是在顶层(如示例中),还是在所有 oneOf 子结构中。

    ¥discriminator property should be required either on the top level, as in the example, or in all oneOf subschemas.

  • 每个 oneOf 子结构必须具有具有鉴别器属性的 properties 关键字。子结构应内联或包含为直接引用(仅允许使用 $ref 关键字,而不允许任何额外关键字)。

    ¥each oneOf subschema must have properties keyword with discriminator property. The subschemas should be either inlined or included as direct references (only $ref keyword without any extra keywords is allowed).

  • 每个 oneOf 子结构中的鉴别器属性的结构必须是 constenum,并且在所有子结构中具有唯一值。

    ¥schema for discriminator property in each oneOf subschema must be const or enum, with unique values across all subschemas.

不满足任何这些要求都会导致结构编译失败。

¥Not meeting any of these requirements would fail schema compilation.

# 所有类型的关键词

¥Keywords for all types

# enum

关键字的值应该是任何类型的唯一项的数组。如果数据深度等于数组中的一项,则该数据有效。

¥The value of the keyword should be an array of unique items of any types. The data is valid if it is deeply equal to one of items in the array.

示例

¥Example

schema:{enum: [2, "foo", {foo: "bar" }, [1, 2, 3]]}

valid:2"foo"{foo: "bar"}[1, 2, 3]

invalid:1"bar"{foo: "baz"}[1, 2, 3, 4],任何不在枚举中的值

¥invalid: 1, "bar", {foo: "baz"}, [1, 2, 3, 4], any value not in enum

# const

该关键字的值可以是任何值。如果数据深度等于关键字的值,则该数据有效。

¥The value of this keyword can be anything. The data is valid if it is deeply equal to the value of the keyword.

示例

¥Example

schema:{const: "foo"}

valid:"foo"

invalid:任何其他值

¥invalid: any other value

使用具有一项的数组,通过 enum 关键字可以实现相同的效果。但 const 关键字不仅仅是 enum 的语法糖。与 $data 参考 结合,它允许定义数据不同部分之间的相等关系。即使使用 $data 引用,也无法使用 enum 关键字实现这一点,因为 $data 不能用来代替一项 - 它只能用于代替 enum 关键字中的整个数组。

¥The same can be achieved with enum keyword using the array with one item. But const keyword is more than just a syntax sugar for enum. In combination with the $data reference it allows to define equality relations between different parts of the data. This cannot be achieved with enum keyword even with $data reference because $data cannot be used in place of one item - it can only be used in place of the whole array in enum keyword.

示例

¥Example

schema:

{
  type: "object",
  properties: {
    foo: {type: "number"},
    bar: {const: {$data: "1/foo"}}
  }
}

valid:{foo: 1, bar: 1}{}

invalid:{foo: 1}{bar: 1}{foo: 1, bar: 2}

# 复合关键词

¥Compound keywords

# not

关键字的值应该是 JSON 结构。如果根据此结构该数据无效,则该数据有效。

¥The value of the keyword should be a JSON Schema. The data is valid if it is invalid according to this schema.

示例

¥Example

schema:{type: "number", not: {minimum: 3}}

valid:12

invalid:34

# oneOf

关键字的值应该是 JSON 结构的数组。如果数据与该数组中的一个 JSON 结构完全匹配,则该数据有效。校验器必须根据所有结构校验数据,以根据此关键字建立有效性。

¥The value of the keyword should be an array of JSON Schemas. The data is valid if it matches exactly one JSON Schema from this array. Validators have to validate data against all schemas to establish validity according to this keyword.

示例

¥Example

schema:

{
  type: "number",
  oneOf: [{maximum: 3}, {type: "integer"}]
}

valid:1.52.545

invalid:234.55.5

# anyOf

关键字的值应该是 JSON 结构的数组。如果根据此数组中的一个或多个 JSON 结构有效,则数据有效。校验器只需要按顺序根据结构校验数据,直到第一个结构匹配(或直到尝试了所有结构)。因此,在大多数情况下,针对此关键字进行校验比针对 "oneOf" 关键字进行校验要快。

¥The value of the keyword should be an array of JSON Schemas. The data is valid if it is valid according to one or more JSON Schemas in this array. Validators only need to validate data against schemas in order until the first schema matches (or until all schemas have been tried). For this reason validating against this keyword is faster than against "oneOf" keyword in most cases.

示例

¥Example

schema:

{
  type: "number",
  anyOf: [{maximum: 3}, {type: "integer"}]
}

valid:1.522.5345

invalid:4.55.5

# allOf

关键字的值应该是 JSON 结构的数组。如果根据此数组中的所有 JSON 结构有效,则数据有效。

¥The value of the keyword should be an array of JSON Schemas. The data is valid if it is valid according to all JSON Schemas in this array.

示例

¥Example

schema:

{
  type: "number",
  allOf: [{maximum: 3}, {type: "integer"}]
}

valid:23

invalid:1.52.544.555.5

# if/then/else

这些关键字允许实现条件校验。它们的值应该是有效的 JSON 结构(对象或布尔值)。

¥These keywords allow to implement conditional validation. Their values should be valid JSON Schemas (object or boolean).

如果 if 关键字不存在,则校验成功。

¥If if keyword is absent, the validation succeeds.

如果数据针对 if 关键字中的子结构有效,则校验结果等于针对 then 关键字中的子结构的数据校验结果(如果 then 不存在,则校验成功)。

¥If the data is valid against the sub-schema in if keyword, then the validation result is equal to the result of data validation against the sub-schema in then keyword (if then is absent, the validation succeeds).

如果数据针对 if 关键字中的子结构无效,则校验结果等于针对 else 关键字中的子结构的数据校验结果(如果 else 不存在,则校验成功)。

¥If the data is invalid against the sub-schema in if keyword, then the validation result is equal to the result of data validation against the sub-schema in else keyword (if else is absent, the validation succeeds).

示例

¥Examples

  1. schema:

    {
      type: "object",
      if: {properties: {foo: {minimum: 10}}},
      then: {required: ["bar"]},
      else: {required: ["baz"]}
    }
    

    valid:

    • {foo: 10, bar: true }

    • {}

    • {foo: 1, baz: true }

    invalid:

    • {foo: 10}bar 为必填项)

      ¥{foo: 10} (bar is required)

    • {foo: 10, baz: true }bar 为必填项)

      ¥{foo: 10, baz: true } (bar is required)

    • {foo: 1}baz 为必填项)

      ¥{foo: 1} (baz is required)

  1. schema:

    {
      type: "integer",
      minimum: 1,
      maximum: 1000,
      if: {minimum: 100},
      then: {multipleOf: 100},
      else: {
        if: {minimum: 10},
        then: {multipleOf: 10}
      }
    }
    

    valid:151020501002005001000

    invalid:

    • -1, 0 (<1)

    • 2000(>1000)

    • 1157123(任何具有多于一位非零数字的整数)

      ¥11, 57, 123 (any integer with more than one non-zero digit)

    • non-integers

# 元数据关键字

¥Metadata keywords

JSON 结构规范定义了几个描述结构本身但不执行任何校验的元数据关键字。

¥JSON Schema specification defines several metadata keywords that describe the schema itself but do not perform any validation.

  • titledescription:有关该结构所表示的数据的信息

    ¥title and description: information about the data represented by that schema

  • $comment:为开发者提供的信息。使用选项 $comment Ajv 记录注释字符串或将注释字符串传递给用户提供的函数。参见 选项

    ¥$comment: information for developers. With option $comment Ajv logs or passes the comment string to the user-supplied function. See Options.

  • default:数据实例的默认值,参见 分配默认值

    ¥default: a default value of the data instance, see Assigning defaults.

  • examples:数据实例的数组。Ajv 不会根据结构检查这些实例的有效性。

    ¥examples: an array of data instances. Ajv does not check the validity of these instances against the schema.

  • readOnlywriteOnly:将数据实例标记为与数据源(数据库、api 等)相关的只读或只写。

    ¥readOnly and writeOnly: marks data-instance as read-only or write-only in relation to the source of the data (database, api, etc.).

  • contentEncodingRFC 2045 (opens new window),例如 "base64"。

    ¥contentEncoding: RFC 2045 (opens new window), e.g., "base64".

  • contentMediaTypeRFC 2046 (opens new window),例如 "image/png"。

    ¥contentMediaType: RFC 2046 (opens new window), e.g., "image/png".

忽略的关键字

Ajv 没有实现关键字 examplescontentEncodingcontentMediaType 的校验,但保留了它们。如果你想创建一个实现其中任何一个的插件,则应该从实例中删除这些关键字。

¥Ajv does not implement validation of the keywords examples, contentEncoding and contentMediaType but it reserves them. If you want to create a plugin that implements any of them, it should remove these keywords from the instance.