JSON 模式
JSON Schema是一种内容规范语言,用于验证 JSON 数据的结构。它可以帮助您指定对象以及对象属性中有效的值。 JSON 模式在提供清晰、人类可读和机器可读的文档方面很有用。
JSON Schema 的结构:因为 JSON 格式包含对象、数组和名称-值对元素。名称-值对用于提供模式处理元素以及验证 JSON 内容。模式处理元素包括(不限于)。
- $schema”指定 JSON 模式的版本。
- 标题和描述:提供有关架构的信息。
- required:它是一个元素数组,指示应该存在哪些元素。
- additionalProperties:指示是否允许存在指定元素。
JSON内容定义:
- 定义 JSON 对象时,JSON 模式使用名称-值对“type”:“object”
- 定义数组时,JSON 模式使用名称-值对“type”:“array”
例子:
{
"$id": "https://example.com/person.schema.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Voters information",
"type": "object",
"properties": {
"firstName": {
"type": "string",
"description": "The person's first name."
},
"lastName": {
"type": "string",
"description": "The person's last name."
},
"age": {
"description": "Age in years which must be equal to or
greater than eighteen in order to vote.",
"type": "integer",
"minimum": 18
}
}
}
输出:
{
"firstName": "Indra",
"lastName": "Sen",
"age": 20
}
上面的 JSON 模式包含以下内容:
- $id关键字
- $schema关键字
- 标题注释关键字
- 属性验证关键字
- 三个键: firstName 、 lastName和age ,每个键都有自己的描述关键字。
- 类型实例数据模型(见上文)
- 年龄键上的最小验证关键字。