【问题标题】:How to enforce only one property value to true in an array (JSON Schema)如何在数组中仅强制一个属性值为真(JSON Schema)
【发布时间】:2020-03-31 23:30:14
【问题描述】:

我正在尝试根据以下输入进行 JSON 验证:

{
  "elements":[
    {
      "..."
      "isSelected": true
    },
    {
      "..."
      "isSelected": false
    },
    {
      "..."
      "isSelected": false
    }    
  ]
}

当且仅当我们将“isSelected”设置为“true”(其余所有设置为“false”)时,输入才会有效。不能多次使用“isSelected: true”(其余的都必须为“false”)。

尝试了以下方法:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "definitions": {
    "element":{
      "type": "object",
      "properties": {
        "isSelected": {
          "type": "boolean"
        }
      }      
    }
  },
  "properties": {
    "elements": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/element"
      },
      "oneOf": [
        {
            "isSelected": true
        }   
      ]
    }
  },

}

【问题讨论】:

    标签: jsonschema


    【解决方案1】:

    不幸的是,我认为 json 架构草案 7 不可能做到这一点。最新草案 (2019-09) 具有 maxContains 关键字,可以验证这一点,但到目前为止,该草案的工具很少.我不知道您正在使用的工具,但如果您能够使用 2019-09,“元素”的架构将类似于:

    {
      "type": "array",
      "contains": {
        "properties": {
          "isSelected": {"const": true}
        }
      },
      "maxContains": 1
    }
    

    oneOf 不是您要查找的内容,为此 - 它检查一组架构中的一个是否针对该实例进行验证,而不是一组实例中的一个是否针对某个架构进行验证。

    【讨论】:

      【解决方案2】:

      目前不支持此功能,但您可能对 this proposal 感兴趣,它打算添加关键字以支持基于键的项目唯一性。不完全一样,但我认为是相关的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-12
        • 1970-01-01
        相关资源
        最近更新 更多