如何定义需要对象数组包含特定值的至少2个属性的JSON模式?

时间:2017-09-08 00:14:54

标签: javascript json validation jsonschema

我有一个如下所示的数据集:

有效示例数据

{
  type: "step",
  label: "Step 1",
  fields: [
    // An optional field
    {
      type: "email",
      label: "Your Email"
    },
    // A field that is required and can be either amount|preset
    {
      type: "amount",
      label: "Amount"
    },
    // A field that is required and can be either credit_card|ach
    {
      type: "credit_card",
      label: "Credit Card"
    }
  ]
}

fields数组可以包含许多不同类型的对象。上面的例子是有效的。

无效的示例数据

{
  type: "step",
  label: "Step 1",
  fields: [
    {
      type: "email",
      label: "Your Email"
    },
    {
      type: "credit_card",
      label: "Credit Card"
    }
  ]
}

这应该是错误,因为它不包含amountpresets

类型的对象

验证规则

为了有效,fields需要包含2个对象。

  • 其中一个必须是{ type: "amount" }{ type: "presets" }

  • 其中一个必须是{ type: "credit_card" }{ type: "ach" }

  • 2的任意组合都会使fields有效。

JSON Schema

这是我的(失败的)JSON架构:

{
  "title": "step",
  "type": "object",
  "properties": {
    "type": {
      "title": "type",
      "type": "string"
    },
    "label": {
      "title": "label",
      "type": "string"
    },
    "fields": {
      "title": "fields",
      "description": "Array of fields",
      "type": "array",
      "additionalItems": true,
      "minItems": 1,
      "items": {
        "type": "object",
        "anyOf": [
          { "properties": { "type": { "enum": ["amount", "preset"] } } },
          { "properties": { "type": { "enum": ["credit_card", "ach"] } } }
        ],
        "properties": {
          "type": {
            "type": "string",
          }
        }
      },
    }
  },
  "required": ["type", "label", "fields"]
}

Here is the JSON Schema Validation Reference

我认为在containsanyOfallOfoneOfenum之间我应该能够做到这一点吗?

1 个答案:

答案 0 :(得分:1)

将以下内容放入/properties/fields架构中。这表达了您需要的约束。删除/properties/fields/items/anyOf(这是错误的)和/properties/fields/additionalItems(它没有做任何事情)。

"allOf": [
  {
    "contains": {
      "properties": { "type": { "enum": ["amount", "presets"] } }
    }
  },
  {
    "contains": {
      "properties": { "type": { "enum": ["credit_card", "ach"] } }
    }
  }
]