首页 > 解决方案 > JSONSchema - if property is true - another field is required

问题描述

I want to create a schema such that when it has the property has_reference the field reference exists (if the field doesn't exist, it is implicitly false). and vice versa. The schema has other fields a and b.

So this is a valid instance:

{
    "a": 1, "b": 2
}
{
    "a": 1, "b": 2
    "has_refernce": true, "reference": "bla"
}

but this is not valid:

{
    "a": 1, "b": 2
    "has_refernce": true
}
{
    "a": 1, "b": 2
    "refernce": "bla"
}

Is this possible?

EDIT: I understand that correct design would be to remove "use_reference" and use null "reference" to indicate whether a reference exists, but I can change the design

标签: jsonjsonschema

解决方案


If you are using the latest version of schema then you can utilize the following hack to achieve this -

    "dependencies": {
      "has_refernce": [
         "reference"
      ],
     "reference": [
         "has_refernce"
      ]
   }

You can also make use of conditions in schema -

"allOf" : [
   {
      "if": {
         "properties": {
            "has_refernce": {
               "const": true
            }
         }
      },
      "then": {
         "required": [
            "reference"
         ]
      }
   }
]

推荐阅读