vinay vishwachandra
vinay vishwachandra

Reputation: 41

Empty object validation in json schema

I'm trying to validate a json using a JSON schema. In the below json "industry" is of type "object" and it is "not required". however i need to find out if "industry" is provided in the json or not.

here is my json schema

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "id": {
      "enum": ["Russia", "Canada"]
    },
    "name": {
      "type": "string"
    },
    "industry": {
      "$ref": "#/definitions/industry"
    }
  },
 "required": [
    "id",
    "name"
    ],
  "definitions": {
      "industry": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "type": {
          "type": "string"
        },
        "codes": {
          "type": "array",
          "items": {
            "type": "integer"
          }
        }
      },
      "required": [
        "codes",
        "type"
      ],
      "title": "industry"
    }
  }
}    

here is my json

{
  "id": "Russia",
  "price": 10.50
}    

I want to know if "industry" object is present or not in the given json bcos if the "industry" object is present in the json. I need to do something else. currently if i send the json as above and try this if statement like below code. It is passing as true even though "industry" object is not present in the json. I believe it is considering "industry" object like this {} and not as null.

    "if":{
      "properties": {"industry" : {  "type": "object" }}
    },    

Any solution to validate if the "industry" object is present in the json object or not will be helpful. Thank you.

Upvotes: 0

Views: 1987

Answers (1)

Ether
Ether

Reputation: 53966

A schema containing "properties" will evaluate to true if the property is not present. What you want to put as the conditional of your "if" is "required":

"if": {"required":["industry"]}, "then": { ... }

Upvotes: 1

Related Questions