首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在json schema中使用`If` `then` ` `else` `条件?

如何在json schema中使用`If` `then` ` `else` `条件?
EN

Stack Overflow用户
提问于 2018-07-26 21:05:45
回答 2查看 32.9K关注 0票数 16

JSON Schema (draft-07)的一个相对较新的添加添加了if、then和else关键字。我不知道如何正确地使用这些新的关键词。以下是我到目前为止的JSON Schema:

代码语言:javascript
运行
复制
{
  "type": "object",
  "properties": {
    "foo": {
      "type": "string"
    },
    "bar": {
      "type": "string"
    }
  },
  "if": {
    "properties": {
      "foo": {
        "enum": [
          "bar"
        ]
      }
    }
  },
  "then": {
    "required": [
      "bar"
    ]
  }
}

如果"foo“属性等于"bar",则"bar”属性是必需的。这与预期的一样。

但是,如果"foo“属性不存在或者输入为空,那么我什么都不想要。如何做到这一点呢?

代码语言:javascript
运行
复制
empty input {}.

发现错误:

代码语言:javascript
运行
复制
     Required properties are missing from object: bar.     Schema path: #/then/required

我使用在线验证工具:

https://www.jsonschemavalidator.net/

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-26 21:22:57

if关键字表示,如果值模式的结果通过验证,则应用then模式,否则应用else模式。

您的模式不起作用,因为您需要在if模式中使用"foo",否则一个空的JSON实例将通过if模式的验证,从而应用需要"bar"then模式。

其次,您需要"propertyNames":false,它可以防止模式中包含任何键,这与设置"else": false不同,后者会使任何内容始终无法通过验证。

代码语言:javascript
运行
复制
{
  "type": "object",
  "properties": {
    "foo": {
      "type": "string"
    },
    "bar": {
      "type": "string"
    }
  },
  "if": {
    "properties": {
      "foo": {
        "enum": [
          "bar"
        ]
      }
    },
    "required": [
      "foo"
    ]
  },
  "then": {
    "required": [
      "bar"
    ]
  },
  "else": false
}
票数 17
EN

Stack Overflow用户

发布于 2018-07-26 21:19:34

不能只使用"else“属性吗?

代码语言:javascript
运行
复制
{
    "type": "object",
    "properties": {
        "foo": { "type": "string" },
        "bar": { "type": "string" }
     },
     "if": {
        "properties": {
            "foo": { 
              "enum": ["bar"] 
            }
        }
    },
    "then": { 
      "required": ["bar"]
    },
    "else": {
      "required": [] 
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51539586

复制
相关文章

相似问题

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