Warm tip: This article is reproduced from stackoverflow.com, please click
json jsonschema node.js

How to use if else condition in JSON Schema Validator

发布于 2020-03-27 10:20:48

I want to use JSON schema validator for Validation while i using code like following i get the error gCode is not defined

I tried like following code

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]
      }

I expected when oemId=1 then gCode is required=true else problemCategoryId is required true

Questioner
rahulshinde5140
Viewed
121
shaochuancs 2019-07-03 22:04

The if-then-else statement of the JSON Schema in question is incorrect. Here is the correct one:

{
  "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"] }
}

Please note this if-then-else syntax is just added to JSON Schema in draft-07, and here its document in json-schema.org: https://json-schema.org/understanding-json-schema/reference/conditionals.html