首页 > 解决方案 > 有一个属性使用 JSON Schema 定义另一个数组属性中的类型吗?

问题描述

鉴于此示例 JSON:

{
  "type": "number",
  "values": [ 34, 42, 99 ]
}

是否可以定义 JSON Schema 以确保values数组的内容是另一个属性中指定的类型(在本例中type)?

上面type是说数组values只能包含整数(使用说明符“数字”)。

或指定values包含字符串:

{
  "type": "string",
  "values": [ "hello", "world" ]
}

标签: jsonschema

解决方案


是的,但是您必须为if/then要支持的每种类型编写一个块。

理解 JSON 模式有一个部分if/then/else:http: //json-schema.org/understanding-json-schema/reference/conditionals.html

这是一个解释如何if/then/else工作的摘录。

例如,假设您想编写一个模式来处理美国和加拿大的地址。这些国家/地区有不同的邮政编码格式,我们希望根据国家/地区选择要验证的格式。如果地址在美国,则 postal_code 字段是“邮政编码”:五位数字后跟可选的四位数字后缀。如果地址在加拿大,则 postal_code 字段是一个六位字母数字字符串,其中字母和数字交替出现。

{
  "type": "object",
  "properties": {
    "street_address": {
      "type": "string"
    },
    "country": {
      "enum": ["United States of America", "Canada"]
    }
  },
  "if": {
    "properties": { "country": { "const": "United States of America" } }
  },
  "then": {
    "properties": { "postal_code": { "pattern": "[0-9]{5}(-[0-9]{4})?" } }
  },
  "else": {
    "properties": { "postal_code": { "pattern": "[A-Z][0-9][A-Z] [0-9][A-Z][0-9]" } }
  }
}

对于您想要支持的每种类型,您都需要编写if/then对象,并将它们全部包装在一个allOf.


推荐阅读