I know there is a similar question here, but it didn't really address my issue. In short, I want one my fields to be dependent on the other field's value. But for some values, I don't want any field to be required. Here is an example:
Schema
{
"definitions": {},
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"colour": {
"type": "string",
"enum": ["red", "black", "blue"]
},
"blackQuote": {
"type": "string",
"maxLength": 11
},
"redQuote": {
"type": "string",
"maxLength": 11
}
},
"oneOf": [
{
"properties": {
"colour": {"enum": ["red"]}
},
"required": ["redQuote"]
},
{
"properties": {
"colour": {"enum": ["black"]}
},
"required": ["blackQuote"]
}
],
"required": [
"colour"
]
}
This works like this:
allOf: (AND) Must be valid against all of the subschemas. anyOf: (OR) Must be valid against any of the subschemas. oneOf: (XOR) Must be valid against exactly one of the subschemas.
Here oneOf is a keyword construct in the JSON Schema, which is used to provide an array of criteria where, if exactly one of them is valid, the whole block is valid. As per the exampe above, objects having ( "email" AND "password" ) OR ( "username" AND "password" ) attributes are considered valid.
There are two forms of dependencies we should look at: Property dependencies which state that if a specified property is present, other properties must be present as well, and. Schema dependencies which define a change in the schema when a given property is present.
JSON Schema is a powerful tool. It enables you to validate your JSON structure and make sure it meets the required API. You can create a schema as complex and nested as you need, all you need are the requirements. You can add it to your code as an additional test or in run-time.
Simplest answer in draft-04 (as noted by Ganesh in a comment):
{
"definitions": {},
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"colour": {
"type": "string",
"enum": ["red", "black", "blue"]
},
"blackQuote": {
"type": "string",
"maxLength": 11
},
"redQuote": {
"type": "string",
"maxLength": 11
}
},
"oneOf": [
{
"properties": {
"colour": {"enum": ["red"]}
},
"required": ["redQuote"]
},
{
"properties": {
"colour": {"enum": ["black"]}
},
"required": ["blackQuote"]
},
{
"properties": {
"colour": {"enum": ["blue"]}
}
}
],
"required": [
"colour"
]
}
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