使用json-schema要求或禁止基于另一个属性值的属性? [英] Use json-schema to require or disallow properties based on another property value?

查看:522
本文介绍了使用json-schema要求或禁止基于另一个属性值的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在json-schema中完成的工作:当属性enabledtrue时,应要求某些其他属性.当false时,这些属性应被禁止.

What I'm trying to accomplish in json-schema: when the property enabled is true, certain other properties should be required. When false, those properties should be disallowed.

这是我的json模式:

Here's my json-schema:

{
  "type": "object",
  "properties": {
    "enabled": { "type": "boolean" }
  },
  "required" : ["enabled"],
  "additionalProperties" : false,
  "if": {
    "properties": {
      "enabled": true
    }
  },
  "then": { 
    "properties": {
      "description" : { "type" : "string" },
      "count": { "type": "number" }
    },
    "required" : ["description", "count"]
  }
}

使用ajv版本6.5进行验证,结果是需要count等,而与enabled的值无关.例如,对于数据:

Validating using ajv version 6.5, this had the result of requiring count, etc. regardless of the value of enabled. For instance, for data:

{ "enabled": false }

我的验证错误是:

[ { keyword: 'required',
    dataPath: '',
    schemaPath: '#/then/required',
    params: { missingProperty: 'description' },
    message: 'should have required property \'description\'' },
  { keyword: 'required',
    dataPath: '',
    schemaPath: '#/then/required',
    params: { missingProperty: 'count' },
    message: 'should have required property \'count\'' },
  { keyword: 'if',
    dataPath: '',
    schemaPath: '#/if',
    params: { failingKeyword: 'then' },
    message: 'should match "then" schema' } ]

如何使用json-schema draft-7完成此操作?

How can I accomplish this using json-schema draft-7?

请注意,此问题与以下问题类似,但要求比以下问题更为严格:
有条件地需要jsonSchema属性.

Note that this question is similar to, but has more stringent requirements than:
jsonSchema attribute conditionally required.

推荐答案

这是受vearutop出色回答的启发.我认为它可能会更短一些,并且可以达到我所说的目的.

This was inspired by vearutop's excellent answer. I think it might be a little shorter, and accomplishes my stated purpose.

{
  "type": "object",
  "oneOf" : [
    {
      "properties": {
        "enabled": { "const": false }
      },
      "required": ["enabled"],
      "additionalProperties": false
    },
    {
      "properties": {
        "enabled": { "const": true },
        "description": { "type": "string" },
        "count": { "type": "number" }
      },
      "required": [ "enabled", "description", "count"],
      "additionalProperties": false
    }
  ]
}

正如评论中所指出的,这是答案.

As pointed out in the comments, this is a specific variant of the Enum strategy spelled out in this answer.

这篇关于使用json-schema要求或禁止基于另一个属性值的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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