首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JSON架构草案4布尔值定义必填字段

JSON架构草案4布尔值定义必填字段
EN

Stack Overflow用户
提问于 2019-09-12 03:30:39
回答 1查看 1K关注 0票数 0

我正在创建一个JSON模式,并且在该模式中有一个布尔变量。当这个布尔值为true时,我希望模式的一些属性是必需的。当这个布尔值为false时,我希望模式的其他属性是必需的。

例如(假装JSON有//注释):

代码语言:javascript
复制
{
   "my_boolean": false,        // boolean which determines which schema to use
   "field1": "someString"      // required when my_boolean is false, optional when true
   "field2": "someOtherString" // required when my_boolean is true, optional when false
}

我假设我想要某种anyOf规范,但是我不知道如何定义"when true do this when false do that“。我遇到了this SO post,而隐含正是我想要的,但是我用来验证的库只支持JSON schema draft 04。

EN

回答 1

Stack Overflow用户

发布于 2019-09-14 02:58:36

隐含模式适用于draft-04。在您引用的SO答案的示例中,唯一在draft-04中不可用的关键字是const。您可以使用单例enum ("const": "foo"变为"enum": ["foo"])。

您的示例将如下所示。它相当冗长,但它做了您需要的事情。

代码语言:javascript
复制
{
  "type": "object",
  "properties": {
    "my_boolean": { "type": "boolean" },
    "field1": { "type": "string" },
    "field2": { "type": "string" }
  },
  "allOf": [
    { "$ref": "#/definitions/my_boolean-true-implies-field1-required" },
    { "$ref": "#/definitions/my_boolean-false-implies-field2-required" }
  ],
  "definitions": {
    "my_boolean-true-implies-field1-required": {
      "anyOf": [
        { "not": { "$ref": "#/defintions/my_boolean-true" } },
        { "required": ["field1"] }
      ]
    },
    "my_boolean-false-implies-field2-required": {
      "anyOf": [
        { "not": { "$ref": "#/defintions/my_boolean-false" } },
        { "required": ["field2"] }
      ]
    },
    "my_boolean-true": {
      "properties": {
        "my_boolean": { "enum": [true] }
      },
      "required": ["my_boolean"]
    },
    "my_boolean-false": {
      "properties": {
        "my_boolean": { "enum": [false] }
      },
      "required": ["my_boolean"]
    }
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57895706

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档