TOC

JSON Schema

json-schema

JSON Schema 是一个 JSON 数据的校验规范,其规则的定义本身也是 JSON 格式。
目前有 RFC 草案。最新是 2022-06-10 提交的 draft-bhutton-json-schema-01

Update @ 2023-02-28: 现在还是没有成为标准。最新的那份草案早已过期(提交之后半年)。

  1. JSON Schema: A Media Type for Describing JSON Documents
  2. JSON Schema Validation: A Vocabulary for Structural Validation of JSON
  3. 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 布尔类型:truefalse
  • 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 布尔

通用规则

  1. title
  2. description
  3. default
  4. required 必需
  5. enum
  6. const
  7. anyOf, oneOf, allOf

Python 示例

采用 Julian/jsonschema GitHub Stars PyPI Downloads
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'

参考资料与拓展阅读