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

Javascript 如何定义JSON模式,该模式要求一个对象数组至少包含2个特定值的属性?,javascript,json,validation,jsonschema,Javascript,Json,Validation,Jsonschema,我的数据集如下所示: 有效示例数据 字段数组可以包含多种类型的对象。上面的例子是有效的 无效的示例数据 这应该是错误的,因为它不包括类型为amount或presets 验证规则 为了有效,字段需要包含2个对象 其中1个必须是{type:“amount”}或{type:“presets”} 其中1个必须是{type:“credit_card”}或{type:“ach”} 2的任何组合都将使字段有效 JSON模式 以下是我的(失败的)JSON模式: { "title": "step",

我的数据集如下所示:

有效示例数据
字段
数组可以包含多种类型的对象。上面的例子是有效的

无效的示例数据 这应该是错误的,因为它不包括类型为
amount
presets

验证规则 为了有效,
字段
需要包含2个对象

  • 其中1个必须是
    {type:“amount”}
    {type:“presets”}

  • 其中1个必须是
    {type:“credit_card”}
    {type:“ach”}

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


我认为在
contains
anyOf
allOf
oneOf
enum
之间,我应该能够做到这一点?

/properties/fields
模式中输入以下内容。这表示了您需要的约束。删除
/properties/fields/items/anyOf
(这是错误的)和
/properties/fields/additionalItems
(它不做任何事情)


非常感谢。还应该注意的是,
contains
仅在v6中实现,一些验证程序库可能不支持它。在这种情况下,它需要从
jsonschema
切换到
ajv
npm libs。@elzi是的,我使用它是因为问题中提到了它。可以在不使用草稿-06的情况下表达
包含的
约束,但这是另一个问题:-)当然!我只是为了将来的读者才提到这一点,而不是你的疏忽:)谢谢。
{
  type: "step",
  label: "Step 1",
  fields: [
    {
      type: "email",
      label: "Your Email"
    },
    {
      type: "credit_card",
      label: "Credit Card"
    }
  ]
}
{
  "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"]
}
"allOf": [
  {
    "contains": {
      "properties": { "type": { "enum": ["amount", "presets"] } }
    }
  },
  {
    "contains": {
      "properties": { "type": { "enum": ["credit_card", "ach"] } }
    }
  }
]