JSON Schema详解

来源:互联网 发布:淘宝男装夏季 编辑:程序博客网 时间:2024/05/16 07:56

熟悉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/

原创粉丝点击