Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible in json schema to define a constraint between two properties

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.

like image 449
kellyfj Avatar asked Jan 12 '15 17:01

kellyfj


People also ask

How do you make a property required in JSON Schema?

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.

What is additional properties in JSON Schema?

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.

How do you reference a JSON Schema in another 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.

What is the purpose of JSON Schema?

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.


2 Answers

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".

like image 111
Andrew Avatar answered Nov 15 '22 05:11

Andrew


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?

like image 28
cloudfeet Avatar answered Nov 15 '22 05:11

cloudfeet