JSON Schema is a vocabulary that allows you to annotate and validate JSON documents.

说人话就是: JSON Schema 定义了如何基于 JSON 格式描述 JSON 数据结构的规范,进而提供数据校验、文档生成和接口数据交互控制等一系列能力。目前还在草案阶段,等待 IETF 工作组验证接收。

还有 JSON Hyper-Schema 就不在这里啰嗦了。

优点

  • describes your existing data format
  • clear, human- and machine-readable documentation: 自描述
  • complete structural validation, useful for
    • automated testing
    • validating client-submitted data

示例

JSON Schema: 文件扩展: 建议为 .schema.json

{
  "$schema": "http://json-schema.org/schema#",
  "title": "Product",
  "type": "object",
  "required": ["id", "name", "price"],
  "properties": {
    "id": {
      "type": "number",
      "description": "Product identifier"
    },
    "name": {
      "type": "string",
      "description": "Name of the product"
    },
    "price": {
      "type": "number",
      "minimum": 0
    },
    "tags": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "stock": {
      "type": "object",
      "properties": {
        "warehouse": {
          "type": "number"
        },
        "retail": {
          "type": "number"
        }
      }
    }
  }
}

The JSON Schema 用来验证下面的 JSON:

{
  "id": 1,
  "name": "Foo",
  "price": 123,
  "tags": [
    "Bar",
    "Eek"
  ],
  "stock": {
    "warehouse": 300,
    "retail": 20
  }
}

参考