【问题标题】:How to define JSON Schema that requires an array of objects to contain at least 2 properties of a certain value?如何定义 JSON Schema 要求一个对象数组包含至少 2 个特定值的属性?
【发布时间】:2018-02-16 19:26:35
【问题描述】:

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

有效示例数据

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

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

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

  • 这两者的任意组合都会使fields 有效。

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 之间我应该能够做到这一点?

【问题讨论】:

    标签: javascript json validation jsonschema


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢。还应该注意,contains 仅在 v6 中实现,一些验证器库可能不支持它。在这种情况下,它需要从 jsonschema 切换到 ajv npm libs。
    • @elzi 是的,我使用它是因为问题中提到了它。可以在没有draft-06 的情况下表达contains 约束,但这是一个不同的问题:-)
    • 当然!我只为未来的读者提到它 - 不是你的任何疏忽:) 非常感谢。
    猜你喜欢
    • 2015-11-04
    • 2018-04-18
    • 2023-03-20
    • 2021-04-17
    • 1970-01-01
    • 2023-02-25
    • 2021-12-08
    • 1970-01-01
    • 2018-03-21
    相关资源
    最近更新 更多