Robin Coe
Robin Coe

Reputation: 750

How can I set a complex json object with an optional property as optional?

Sorry if the question is confusing. I'm trying to get my head around jsonschema validation. The problem I'm trying to solve is to set a property as optional. The property belongs to a required object that is, in turn, a property of the complex type.

e.g.

{ "prop1" : {
              "field1" : {"type" : "string" },
              "field2" : {"type" : "string" }
           },
  "prop2" : { "type" : "string" }
}

If I want to declare that prop1 is required but prop1.field1 is optional, how do I do that with jsonschema?

Thanks, Robin

Upvotes: 2

Views: 5841

Answers (1)

damorin
damorin

Reputation: 1504

you need to specify "required" at the same level as the "properties".

{
  "type": "object",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "properties": {
    "prop1": {
      "type": "object",
      "properties": {
        "field1": {
          "type": "object",
          "properties": {
            "type": {
              "type": "string"
            }
          }
        },
        "field2": {
          "type": "object",
          "properties": {
            "type": {
              "type": "string"
            }
          }
        }
      }
    },
    "prop2": {
      "type": "object",
      "properties": {
        "type": {
          "type": "string"
        }
      }
    }
  },
  "required" : [ "prop1" ]
}

This schema was generated with this online tool (plus some editing):

JSON Schema tool

Upvotes: 4

Related Questions