Anna Melzer
Anna Melzer

Reputation: 1613

JSON schema: schemas in types

I am trying to create a complex JSON schema that tries to use conditional dependencies without having access to OneOf, AnyOf etc

I am basically trying to combine

const schema1 = {
    type: "object",
    properties: {
        q1: {
            type: "boolean",
            enum: [false]
        }
    },
    required: ["q1"]
}

and

const schema2 = {
    type: "object",
    properties: {
        q1: {
            type: "boolean",
            enum: [true]
        }
        sq1: {
            type: "boolean"
        }
    },
    required: ["q1", "sq1"]
}

into one schema combined_schema thus mocking the conditional dependency requiring an answer for sq1 if the answer for q1 was true.

In the JSON schema wiki I was reading that AnyOf would replace the "schema" in types" but looking at the example I am unsure of how that could be used in a specific case (The {"schema1": "here"} part is very confusing.

https://github.com/json-schema/json-schema/wiki/anyOf,-allOf,-oneOf,-not

Could anybody please help me apply the wiki example to my real world problem?

Upvotes: 1

Views: 209

Answers (2)

esp
esp

Reputation: 7677

The schema your answer is not a valid JSON-schema. You can do it with anyOf keyword:

{
    type: "object",
    required: ["q1"]
    anyOf: [
        {
            properties: {
                q1: { enum: [false] } // no need for type here
            }
        },
        {
            properties: {
                q1: { enum: [true] },
                sq1: { type: "boolean" }
            },
            required: ["sq1"]
        }
    ]
}

There is also the keyword switch from JSON-Schema v5 proposals implemented in Ajv (Disclaimer: I created it).

Upvotes: 1

Anna Melzer
Anna Melzer

Reputation: 1613

I found the answer. They key is using refs

{
    "type": [
                {"$ref": "#/schema1"},
                {"$ref": "#/schema2"}
            ],
    "schema2":{
        "type": "object",
        "properties": {
            "q1": {
                "type": "boolean",
                "enum": [true]
            },
            "sq1": {
                "type": "boolean"
            }
        },
    "required": ["q1", "sq1"]
    },
    "schema1": {
        "type": "object",
        "properties": {
            "q1": {
                "type": "boolean",
                "enum": [false]
            }
        },
        "required": ["q1"]
    }
}

Upvotes: 1

Related Questions