我该如何在json模式中使用if then else条件? [英] How do I use the `If` `then` `else` condition in json schema?

查看:147
本文介绍了我该如何在json模式中使用if then else条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相对较新的JSON模式(草案07)添加了if,then和else关键字.我无法解决如何正确使用这些新关键字的问题.到目前为止,这是我的JSON模式:

A relatively new addition to JSON Schema (draft-07) adds the if, then and else keywords. I cannot work out how to use these new key words correctly. Here is my JSON Schema so far:

{
  "type": "object",
  "properties": {
    "foo": {
      "type": "string"
    },
    "bar": {
      "type": "string"
    }
  },
  "if": {
    "properties": {
      "foo": {
        "enum": [
          "bar"
        ]
      }
    }
  },
  "then": {
    "required": [
      "bar"
    ]
  }
}

如果"foo"属性等于"bar",则需要"bar"属性.这可以按预期工作.

If the "foo" property equals "bar", Then the "bar" property is required. This works as expected.

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

However, if the "foo" property does not exist or input is empty then I don't want anything. how to acheive this?

empty input {}.

发现错误:
对象:栏缺少必需的属性. 架构路径:#/then/required

Found Errors:
Required properties are missing from object: bar. Schema path: #/then/required

我使用在线验证工具:

https://www.jsonschemavalidator.net/

推荐答案

if关键字表示,如果值架构的结果通过验证,则应用then架构,否则应用else架构.

The if keyword means that, if the result of the value schema passes validation, apply the then schema, otherwise apply the else schema.

您的架构无效,因为您需要在if架构中要求"foo",否则空的JSON实例将通过对if架构的验证,因此应用then架构,这需要"bar".

Your schema didn't work because you needed to require "foo" in your if schema, otherwise an empty JSON instance would pass validation of the if schema, and therefore apply the then schema, which requires "bar".

第二,您需要"propertyNames":false,它可以防止架构中包含任何键,这与您要设置"else": false的情况不同,因为这会使任何内容始终无法通过验证.

Second, you want "propertyNames":false, which prevents having any keys in the schema, unlike if you were to set "else": false which would make anything always fail validation.

{
  "type": "object",
  "properties": {
    "foo": {
      "type": "string"
    },
    "bar": {
      "type": "string"
    }
  },
  "if": {
    "properties": {
      "foo": {
        "enum": [
          "bar"
        ]
      }
    },
    "required": [
      "foo"
    ]
  },
  "then": {
    "required": [
      "bar"
    ]
  },
  "else": false
}

这篇关于我该如何在json模式中使用if then else条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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