JSON Schema 是一个 JSON 数据的校验规范,其规则的定义本身也是 JSON 格式。
目前有 RFC 草案。最新是 2022-06-10 提交的 draft-bhutton-json-schema-01。
Update @ 2023-02-28: 现在还是没有成为标准。最新的那份草案早已过期(提交之后半年)。
- JSON Schema: A Media Type for Describing JSON Documents
- JSON Schema Validation: A Vocabulary for Structural Validation of JSON
- Relative JSON Pointers
示例
{
  "type": "object",
  "properties": {
    "number": { "type": "number" },
    "street_name": { "type": "string" },
    "street_type": {
      "type": "string",
      "enum": ["Street", "Avenue", "Boulevard"]
    }
  }
}
关键字
数据类型(type 关键字)
- string字符串
- integer整数
- number数字,包括整数、浮点数
- boolean布尔类型:- true,- false
- object对象
- array数组
- null空值
字符串
- 
format格式,默认只是注释,验证器实现也可以根据这个来进行校验。
- 
date
- time
- date-time
- uri
- email
- ipv4
- 
ipv6
- 
pattern正则表达式
数值(number,integer)
- minimum大于等于
- exclusiveMinimum大于,部分版本中,这个值是 bool 型
- maximum小于等于
- exclusiveMaximum小于,部分版本中,这个值是 bool 型
- multipleOf倍数
对象
- properties
- patternProperties
- additionalProperties
数组
- items
- additionalItems
- minItems 整数
- maxItems 整数
- uniqueItems 布尔
通用规则
- title
- description
- default
- required 必需
- enum
- const
- anyOf, oneOf, allOf
Python 示例
采用 Julian/jsonschema  
PS:现在仓库地址转向了 python-jsonschema/jsonschema
>>> from jsonschema import validate
>>> # A sample schema, like what we'd get from json.load()
>>> schema = {
...     "type" : "object",
...     "properties" : {
...         "price" : {"type" : "number"},
...         "name" : {"type" : "string"},
...     },
... }
>>> # If no exception is raised by validate(), the instance is valid.
>>> validate(instance={"name" : "Eggs", "price" : 34.99}, schema=schema)
>>> validate(
...     instance={"name" : "Eggs", "price" : "Invalid"}, schema=schema,
... )                                   # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
    ...
ValidationError: 'Invalid' is not of type 'number'
参考资料与拓展阅读
- Wikipedia, JSON, Metadata and schema
- JSON Schema, Specification
 https://www.cnblogs.com/dreamyu/p/9317721.html
- JSON Schema, Understanding JSON Schema
- Apifox,JSON Schema 规范(中文版)
- JSON-Schema-Editor 编辑器,https://hellosean1025.github.io/json-schema-visual-editor/
