温馨提示:本文翻译自stackoverflow.com,查看原文请点击:node.js - How to use if else condition in JSON Schema Validator
json jsonschema node.js

node.js - 如何在JSON模式验证器中使用if else条件

发布于 2020-03-27 10:53:39

我想使用JSON模式验证器进行验证,而我使用如下代码获得错误gCode却未定义

我尝试像下面的代码

properties: {
        oemId: {
          'type': ['integer'],
          'minLength': 1,
          'required': true
        },
        gCode:{
          'type': ['string'],
          'minLength': 1
        },
        problemCategoryId: {
          'type': ['integer'],
          'minLength': 1
        }
      },
      if :{
        properties:{
          oemId: 1
        }
      },
      then:{
        required:[gCode]
      },
      else:{
        required: [problemCategoryId]
      }

我期望当oemId = 1时需要gCode = true否则问题problemCategoryId必须为true

查看更多

查看更多

提问者
rahulshinde5140
被浏览
234
shaochuancs 2019-07-03 22:04

if-then-else讨论的JSON模式语句不正确。这是正确的:

{
  "type": "object",
  "properties": {
        oemId: {
          'type': ['integer'],
          'minLength': 1,
          'required': true
        },
        gCode:{
          'type': ['string'],
          'minLength': 1
        },
        problemCategoryId: {
          'type': ['integer'],
          'minLength': 1
        }
  },
  "if": {
    "properties": {
      "oemId": { "const": 1 }
    },
    "required": ["oemId"]
  },
  "then": { "required": ["gCode"] },
  "else": { "required": ["problemCategoryId"] }
}

请注意,此if-then-else语法只是在draft-07的 JSON Schema中添加了,这里是json-schema.org中的文档:https ://json-schema.org/understanding-json-schema/reference/conditionals.html