JSON Schema based on property values – use of OneOf

Hi, all:

This is about JSON schema draft version 4. Let’s say if you want a given property of a JSON object to be required or optional based on another property’s value. For example, when status is Error, the statusDesc is required; when status is Success, the statusDesc is optional.

{
“status”: “Error”,
“statusDesc”: “Database Error”
}

vs.

{
“status”: “Success”
}

The easy one to do it is to use OneOf (or AnyOf). The OneOf allows to select the required array[] based on the value of status from its enum array []. It is quite verbose, but there is no other simpler way to do as far as I know.

{
“$schema”: “http://json-schema.org/draft-04/schema#”,
“title”: “OneOf Example”,
“description”: “This schema can choose properties or requirements based on certain value”,
“type”: “object”,
“oneOf”: [
{
“properties”: {
“status”: {
“description”: “The status of the transaction”,
“type”: “string”,
“enum”: [
“Success”
]
},
“statusDesc”: {
“description”: “The detailed description of status. Optional when Success”,
“type”: “string”
}
},
“required”: [
“status”
]
},
{
“properties”: {
“status”: {
“description”: “The status of the transaction”,
“type”: “string”,
“enum”: [
“Error”
]
},
“statusDesc”: {
“description”: “The detailed description of status. Required when Error”,
“type”: “string”
}
},
“required”: [
“status”,
“statusDesc”
]
}
]
}

Cheers!