json schema step by step 2022-10-26

本文对json schema做基本的介绍
更多语法可访问官网,有详细的例子:http://json-schema.org/understanding-json-schema/

step1 $schema & type

# schema0
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "string"
}

The $schema keyword is used to declare which dialect of JSON Schema the current schema was written for. The value of the $schema keyword is also [the identifier for a schema that can be used to verify that the current schema is valid]. A schema that describes another schema is called a “meta-schema”.
$schema的值是另一个schema的id,表示使用目标元schema检查当前编写的schema是否valid

type keyword is used to specify the value's type. basic types are the following:

string number integer object array boolean null

In the following example, we accept strings and numbers, but not structured data types:
{ "type": ["number", "string"] }
而每一种type下又有各自支持的其他keyword

# 如`{ "type": "string" }`还支持`minLength``maxLength`和`regex`对string做进一步限制
{
  "type": "string",
  "minLength": 2,
  "maxLength": 3,
  "pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$"
}

# 0 <= value < 100
{
  "type": "number",
  "minimum": 0,
  "exclusiveMaximum": 100
}

so, "i am a string" fits schema0, but ["hhh"] not

step2 enum & const

The enum keyword is used to restrict a value to a fixed set of values. It must be an array with at least one element, where each element is unique.

we can use enum even without a type, to accept values of different types. Let’s extend the example to use null to indicate “off”, and also add 42, just for fun.

{
  "enum": ["red", "amber", "green", null, 42]
}

The const keyword is used to restrict a value to a single value.

# schema1
{"const": "United States of America"}

only string "United States of America" fits schema1

step3 Schema Composition

allOf: (AND) Must be valid against all of the subschemas
anyOf: (OR) Must be valid against any of the subschemas
oneOf: (XOR) Must be valid against exactly one of the subschemas
http://json-schema.org/understanding-json-schema/reference/combining.html

tools:
create related jsonschema according to json
json schema validator

你可能感兴趣的:(json schema step by step 2022-10-26)