JSON Schemas have a required property, which lists the required fields in a JSON object. For example, the following (simplified) schema validates a call that sends a text message to a user:
{
"type": "object",
"properties": {
"userId": { "type": "string" },
"text": { "type": "string" },
},
"required": ["userId", "text"]
}
Suppose that I want to enable sending the message to multiple users, i.e. have either a userId field, or an array of userIds (but not both or neither). Is there a way to express such a condition in a JSON Schema?
Naturally, there are ways to overcome the problem in this case - for example, a userId array with a single element - but the general case is interesting and useful.
You've probably sorted this out by now, but this will do the trick using oneOf on the type of the field.
{
"type": "object",
"properties": {
"userId": {
"oneOf": [
{
"type": "string"
},
{
"type": "array",
"items": {
"type": "string"
}
}
]
},
"text": {
"type": "string"
}
},
"required": ["userId", "text"]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With