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

How to define JSON Schema that requires an array of objects to contain at least 2 properties of a certain value?

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

有效示例数据

{
  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 个对象。

JSON 架构

这是我的(失败)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 之间我应该可以做到这一点?

将以下内容放入您的 /properties/fields 架构中。这表达了你需要的约束。删除 /properties/fields/items/anyOf(这是错误的)和 /properties/fields/additionalItems(它什么都不做)。

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