熟悉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規範組成
- JSON Schema Core
- JSON Schema Validation
- JSON Hyper-Schema
3. 規範概覽
1)Type-specific keywords
{ "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"] }
2)Generic keywords
{
"title" : "Match anything",
"description" : "This is a schema that matches anything.",
"default" : "Default value"
}
3)Combining schemas
- not
{ "not": { "type": "string" } }
- allOf
{
"allOf": [
{ "type": "string" },
{ "maxLength": 5 }
]
}
- anyOf
{
"anyOf": [
{ "type": "string", "maxLength": 5 },
{ "type": "number", "minimum": 0 }
]
}
- oneOf
{
"oneOf": [
{ "type": "number", "multipleOf": 5 },
{ "type": "number", "multipleOf": 3 }
]
}
4)$schema keyword
"$schema": "http://json-schema.org/schema#"
"$schema": "http://json-schema.org/draft-06/schema#"
5)Regular Expressions
6) $ref keyword
- 基本複用
{ "$ref": "#/currentdoc/definitions/address" }
或
{ "$ref": "asidedoc_definitions.json#/address" }
- id設定基本URI
"id": "http://foo.bar/schemas/address.json"
{ "$ref": "person.json" }
- 擴充複用
"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"]
}
]
}
4. 解析軟體
- Java
https://github.com/everit-org/json-schema
https://github.com/java-json-tools/json-schema-validator
https://github.com/networknt/json-schema-validator
- Python
https://github.com/Julian/jsonschema
https://github.com/zyga/json-schema-validator
- Online
http://jsonschemalint.com/
參考連結:
http://json-schema.org/