I'm trying to implement this condition: field is required based on value of another field i.e. if request with "index":"true" exists then "id" element required: true.
Here is a sample schema:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "test title",
"type": "object",
"properties": {
"data": {
"type": "array",
"items": {
"$ref": "#/definitions/Item"
},
"minItems": 0
}
},
"required": [
"data"
],
"definitions": {
"Item": {
"type": "object",
"properties": {
"id": {
"type": [
"integer",
"string"
]
},
"type": {
"type": "string"
}
}
}
}
}
How it can be implemented?
Any pointers will be helpful.
Required Properties By default, the properties defined by the properties keyword are not required. However, one can provide a list of required properties using the required keyword. The required keyword takes an array of zero or more strings. Each of these strings must be unique.
In a JSON schema, a $ref keyword is a JSON Pointer to a schema, or a type or property in a schema. A JSON pointer takes the form of A # B in which: A is the relative path from the current schema to a target schema. If A is empty, the reference is to a type or property in the same schema, an in-schema reference.
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.
JSON Schema is a JSON-based format for defining the structure of JSON data. It provides a contract for what JSON data is required for a given application and how to interact with it. It can be used for validation, documentation, hyperlink navigation, and interaction control of JSON data.
Your sample chema is strange for me, but for validation case in ticket description your can use this part of json shema:
"properties": {
"data": {
"oneOf": [
{
"type": "object",
"required": [
"index"
],
"properties": {
"index": {
"type": "boolean",
"enum": [false]
}
}
},
{
"type": "object",
"required": [
"index",
"id"
],
"properties": {
"index": {
"type": "boolean",
"enum": [true]
},
"id": {
"type": "boolean"
}
}
}
]
}
}
This trick helps for you, if you want validate one parameter, when other parameters equals to some value.
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