熟悉XML的开发人员都知道,对XML文档的定义有一个XML Schema。
同样,对于JSON文件的定义,也应该有一个JSON Schema以规范JSON文件内容。
JSON Schema用以标注和验证JSON文档的元数据的文档,可以类比于XML Schema。相对于JSON Schema,一个JSON文档就是JSON Schema的一个instance。
1.JSON Schema规范
IETF负责起草相关规范
最新版本是2017-4-15发布的Draft 6
http://json-schema.org/draft-06/schema
2. JSON Schema规范组成
{ "type": "string",
"pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$",
"minLength": 2,
"maxLength": 3,
"format": "date-time|email|hostname|ipv4|ipv6|uri" }
{ "type": "number",
"minimum": 0,
"maximum": 100 }
{ "type": "integer" }
{ "type": "object",
"properties": {
"name": { "type": "string" },
"credit_card": { "type": "number" }
},
"required": ["name"] }
{ "type": "array",
"minItems": 2,
"maxItems": 3,
"items": {
"type": "number"
} }
{ "type": "boolean" }
{ "type": "null" }
{ "type": ["number", "string"] }
{
"title" : "Match anything",
"description" : "This is a schema that matches anything.",
"default" : "Default value"
}
{ "not": { "type": "string" } }
{
"allOf": [
{ "type": "string" },
{ "maxLength": 5 }
]
}
{
"anyOf": [
{ "type": "string", "maxLength": 5 },
{ "type": "number", "minimum": 0 }
]
}
{
"oneOf": [
{ "type": "number", "multipleOf": 5 },
{ "type": "number", "multipleOf": 3 }
]
}
{ "$ref": "#/currentdoc/definitions/address" }
或
{ "$ref": "asidedoc_definitions.json#/address" }
"shipping_address": {
"allOf": [
// Here, we include our "core" address schema...
{ "$ref": "#/definitions/address" },
// ...and then extend it with stuff specific to a shipping
// address
{ "properties": {
"type": { "enum": [ "residential", "business" ] }
},
"required": ["type"]
}
]
}
参考链接:
http://json-schema.org/