JSON Schema

JSON Schema


Notes

Type-specific keywords

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

  • type:stringnumberintegerobjectarraybooleannull

  • with type string

    • Length:minLengthmaxLength

    • pattern(正则表达式)

    • Dates and times

      • date-time2018-11-13T20:20:39+00:00

      • time20:20:39+00:00

      • date2018-11-13

      • durationP3D(3 天)

    • Hostnames:hostnameidn-hostname

    • IP Addresses:ipv4ipv6

    • Resource identifiers:uuiduriuri-referenceiriiri-reference

    • URI template:uri-template

    • JSON Pointer:json-pointerrelative-json-pointer

    • Regular Expressions:regex

  • with type number

    • multiples:multipleOf(倍数,可以设置成任何正数)

    • range:minimumexclusiveMinimumexclusiveMinimummaximumexclusiveMaximum

  • with type object

    • properties

    • patternProperties:正则表达式用于 key

    • additionalProperties:如果为 false,那么不允许有其他的 propertites

    • unevaluatedProperties:类似于additionalProperties,只是它可以识别在子架构中声明的属性。

    • required:必须包含的properties,是一个array

    • propertyNames:属性名称。如果您不想强制使用特定的属性,但又想确保这些属性的名称遵循特定的约定,那么这会很有用。

    • 属性的数量:minPropertiesmaxProperties

例如:

{
  "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 的属性
}
  • with type array

    • prefixItems:元组验证(一个固定长度的序列,其中每个项目可能具有不同的模式)

    • unevaluatedItems:数组中添加或禁止额外项时有用和 items 有点像

    • items:列表验证(一个任意长度的序列,其中每个项目匹配相同的模式)。items用来验证超出prefixItems中定义的元素是否有效,如果为 false 则不能包含其他项目

    • minItemsmaxItems:数组长度

    • contains:有一个满足就行

    • minContainsmaxContains:进一步控制 contains 达标的数量

    • uniqueItems:确保数组中的每个项都是唯一的

{
  "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
}
  • with type boolean(只能是 true 或 false)

  • with type null(只能是 null,其他的比如 false,0,"" 都不可以)

Schema Composition

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

  • allOf: (AND) Must be valid against all of the subschemas

  • anyOf: (OR) Must be valid against any of the subschemas

  • oneOf: (XOR) Must be valid against exactly one of the subschemas

  • not:非

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" } }

最后更新于

这有帮助吗?