Is it possible in json schema to define a constrai

2020-07-18 08:49发布

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.

2条回答
beautiful°
2楼-- · 2020-07-18 09:21

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

查看更多
姐就是有狂的资本
3楼-- · 2020-07-18 09:33

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?

查看更多
登录 后发表回答