As a JSON Schema user, I want to require certain properties based on the numeric value of another property.
An example case here is that I have a system where user can purchase a bus ticket (with value of 1) or a train ticket (with value of 2). If a train ticket is purchased, a seat must be included as tickets are tied to a specific seat but with bus, such requirement does not exist.
Bus ticket data
{
"ticket_type": 1
}
Train ticket data
{
"ticket_type": 2,
"seat": 42
}
To validate this, our schema looks something like this:
{
"$id": "https://example.com",
"$schema": "https://json-schema.org/draft-04/schema",
"type": "object",
"properties": {
"ticket_type": { "type": "integer" },
"seat": { "type": "integer" }
},
"required": ["ticket_type"],
"oneOf": [
{
"properties": { "ticket_type": { "const": 1 } }
},
{
"properties": { "ticket_type": { "const": 2 } },
"required": ["seat"]
}
]
}
Here we define our two properties, ticket_type
and seat
. In oneOf
restrictions, we require one of the two rules to match: either ticket_type
equals 1 or ticket_type
equals 2 AND seat
is required.
If we want to instead do ranges (for example, require seat for any ticket_type
that is larger than zero), we do:
{
"$id": "https://example.com",
"$schema": "https://json-schema.org/draft-04/schema",
"type": "object",
"properties": {
"ticket_type": { "type": "integer" },
"seat": { "type": "integer" }
},
"required": ["ticket_type"],
"oneOf": [
{
"properties": { "ticket_type": { "const": 0 } }
},
{
"properties": { "ticket_type": { "minimum": 1 } },
"required": ["seat"]
}
]
}