jsonschema - 使用 json-schema 来要求或禁止基于另一个属性值的属性?

我试图在 json-schema 中完成的工作:当属性 enabledtrue 时,应该需要某些其他属性。当 false 时,应禁止使用这些属性。

这是我的 json 架构:

{
  "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 的值如何。例如,对于数据:

{ "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 完成此操作?

请注意,此问题与以下问题类似,但要求更严格:
jsonSchema attribute conditionally required .

最佳答案

试试这个模式:

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

如果您需要 "additionalProperties": false,您必须在 thenelse 中枚举所有属性。如果您可以接受额外的属性,架构可能会更简单:

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

我检查了 ajv cli .

有效:{"enabled": false}

无效:{"enabled": true}

有效:{"enabled": true, "description":"hi", "count":1}

https://stackoverflow.com/questions/50340967/

相关文章:

apache-spark - Pyspark - 圆时间表示为最接近刻钟(15 分钟)的整数

ansible - 例如,如何限制 Ansible 的设置模块 (gather_facts) 仅检索

typescript - 在 Typescript 中构建 const 键的类型

wordpress - 使用 AWS RDS 和我自己的数据库哪个最便宜?

amazon-web-services - 如何在不使用 IAM 的情况下允许第三方文件上传到私有(

reactjs - 无法使用 axios 和 ReactJS 执行获取请求

apache-spark - Spark UI 中的 "red"executors 是什么意思?

python - 如何永远运行异步函数(Python)

android - 使用限制查询 Firebase 数据库

python - 使用 bigquery tables GET api 获取表的最后修改日期