如何在数组中仅将一个属性值强制为true(JSON架构) [英] How to enforce only one property value to true in an array (JSON Schema)

查看:150
本文介绍了如何在数组中仅将一个属性值强制为true(JSON架构)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

当且仅当我们将"isSelected"设置为"true"(其余所有设置为"false")时,输入才有效.不能多次拥有"isSelected:true"(其余所有属性都必须为"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").

尝试以下操作:

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

}

推荐答案

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

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并不是您想要的,为此-它检查一组模式之一是否针对该实例进行验证,而不是一组实例之一是否针对某个模式进行验证.

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.

这篇关于如何在数组中仅将一个属性值强制为true(JSON架构)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆