JSON Schema


Notes

Type-specific keywords

https://json-schema.org/understanding-json-schema/reference/type

例如:

{
  "type": "object",
  "properties": {
    "number": { "type": "number" },
    "street_name": { "type": "string" },
    "street_type": { "enum": ["Street", "Avenue", "Boulevard"] }
  },
  "patternProperties": {
    "^S_": { "type": "string" }, <- 任何 S_ 开头的key 对应的 value 都必须是 string
  }
  "additionalProperties": false,
  // "additionalProperties": { "type": "string" } <- 这样就可以允许 string 的属性
}
{
  "type": "array",
  "prefixItems": [
    { "type": "number" },
    { "type": "string" },
    { "enum": ["Street", "Avenue", "Boulevard"] },
    { "enum": ["NW", "NE", "SW", "SE"] }
  ],
  "items": false
}
{
  "prefixItems": [
    { "type": "string" }, { "type": "number" }
  ],
  "unevaluatedItems": false
}

Schema Composition

https://json-schema.org/understanding-json-schema/reference/combining#schema-composition

Examples:

需要同时满足

{
  "allOf": [
    { "type": "string" },
    { "maxLength": 5 }
  ]
}

满足其一就行

{
  "anyOf": [
    { "type": "string", "maxLength": 5 },
    { "type": "number", "minimum": 0 }
  ]
}

满足一个

{
  "oneOf": [
    { "type": "number", "multipleOf": 5 },
    { "type": "number", "multipleOf": 3 }
  ]
}

{ "not": { "type": "string" } }