How to enforce only one property value to true in an array (JSON Schema)

与世无争的帅哥 提交于 2020-04-14 07:36:10

问题


I am trying to have JSON validation based on the following input:

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

The input is going to be valid if and only if we have "isSelected" set to "true" (and all the rest set to "false"). Can't have "isSelected: true" more than once (and all the rest need to be "false").

Tried with the following:

{
  "$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
        }   
      ]
    }
  },

}

回答1:


unfortunately I don't think this is possible with json schema draft 7. the newest draft (2019-09) features the maxContains keyword, which would be able to validate this, but tooling for this draft is sparse so far. I don't know the tooling you're using, but if you are able to use 2019-09, the schema for 'elements' would look something like:

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

oneOf isn't what you're looking for, for this - it checks that one of a set of schemas validates against the instance, not whether one of a set of instances validates against a schema.




回答2:


This is not currently supported, but you may be interested in this proposal which intends to add a keyword to support key-based item uniqueness. It's not exactly the same, but I think it's related.



来源:https://stackoverflow.com/questions/60961471/how-to-enforce-only-one-property-value-to-true-in-an-array-json-schema

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!