0

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

user972014
  • 3,296
  • 6
  • 49
  • 89
  • 1
    why don't you just put the `reference` as on optional field and remove the `has_reference`? – hek2mgl Jan 04 '20 at 08:49
  • Does this answer your question? [jsonSchema attribute conditionally required](https://stackoverflow.com/questions/38717933/jsonschema-attribute-conditionally-required) – Jason Desrosiers Jan 04 '20 at 21:25

2 Answers2

3

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"
         ]
      }
   }
]
Ashutosh
  • 917
  • 10
  • 19
  • The `dependencies` keyword has been available since draft-04. You don't need draft-07. In the latest draft 2019-09, `dependencies` was split into two keywords, `dependentRequired` and `dependentSchemas`. The way it's used in this example would be the `dependentRequired` keyword. – Jason Desrosiers Jan 04 '20 at 21:25
1

if you rewrite like this it will be easier to add "required" keyword:

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

you can try using the "required" keyword but only for the element inside "ref". Your schema would look like this:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "a": {
      "type": "integer"
    },
    "b": {
      "type": "integer"
    },
    "ref": {
      "type": "object",
      "properties": {
        "has_refernce": {
          "type": "boolean"
        },
        "reference": {
          "type": "string"
        }
      },
    "required" : [ "has_refernce", "reference" ]
    }
  },
  "required": [
    "a",
    "b"
  ]
}

So only a and b are required but as soon as "ref" is defined than both "has"refernce" and "reference" will be required.

Hope this help.

damorin
  • 1,389
  • 1
  • 12
  • 15