I have two fields in my schema - one is a required property called "name" and the other is optional (used to define a sorting property) called "nameSort" and I want to express
If the "nameSort" field is defined, the "name" field should also be defined as the same value.
Is it possible to express such an "inter-element" constraint with JSON schema? My cursory read of JSON Schema here http://json-schema.org/latest/json-schema-validation.html says no.
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.
The value of "additionalProperties" MUST be a boolean or an object. If it is an object, it MUST also be a valid JSON Schema. The value of "properties" MUST be an object. Each value of this object MUST be an object, and each object MUST be a valid JSON Schema.
A schema can reference another schema using the $ref keyword. The value of $ref is a URI-reference that is resolved against the schema's Base URI. When evaluating a $ref , an implementation uses the resolved identifier to retrieve the referenced schema and applies that schema to the instance.
JSON Schema is a lightweight data interchange format that generates clear, easy-to-understand documentation, making validation and testing easier. JSON Schema is used to describe the structure and validation constraints of JSON documents.
Old question, but this can now be done with json schema v5/v6 using a combination of the constant
and $data
(JSON pointer or relative JSON pointer) keywords.
Example:
"properties": {
"password": { "type": "string" },
"password_confirmation": { "const": { "$data": "1/password" } }
}
Where "1/password"
is a relative JSON pointer saying "go up one level, then look up the key password".
You can express one property must be defined when another is present, e.g.:
{
"type": "object",
"dependencies": {
"nameSort": ["name"]
}
}
However, you cannot specify that two properties must have equal values.
Also, why do you have a separate property at all, if it's always going to be equal? And if it's always equal, could you just have a boolean flag to reduce redundancy?
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