Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make json-schema to allow one but not another field?

Is it possible to make jsonschema to have only one of two fields.

For example, image if I want to have a JSON with ether start_dt or end_dt but not both of them at the same time. like this:

OK

{
    "name": "foo",
    "start_dt": "2012-10-10"
} 

OK

{
    "name": "foo",
    "end_dt": "2012-10-10"
} 

NOT OK

{
    "name": "foo",
    "start_dt": "2012-10-10"
    "end_dt": "2013-11-11"
} 

What should I add to the schema:

{ 
    "title": "Request Schema",
    "type": "object",
    "properties": {
        "name": 
            {   
                "type": "string"
            },  
        "start_dt": 
            {
                "type": "string",
                "format": "date"

            },
        "end_dt":
            {
                "type": "string",
                "format": "date"
            }
    }
}
like image 435
Vor Avatar asked Oct 17 '13 20:10

Vor


People also ask

What does exclusion minimum property in JSON Schema mean?

Gets or sets a flag indicating whether the value can not equal the number defined by the minimum attribute (Minimum).

What is allOf in JSON Schema?

By the definition of this keyword, it meant that the instance had to be valid against the current schema and all schemas specified in extends ; basically, draft v4's allOf is draft v3's extends .

What is JSON Schema additionalProperties?

The additionalProperties keyword is used to control the handling of extra stuff, that is, properties whose names are not listed in the properties keyword or match any of the regular expressions in the patternProperties keyword. By default any additional properties are allowed.

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.


1 Answers

You can express this using oneOf. This means that the data must match exactly one of the supplied sub-schemas, but not more than one.

Combining this with required, this schema says that instances must either define start_dt, OR define end_dt - but if they contain both, then it is invalid:

{
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "start_dt": {"type": "string", "format": "date"},
        "end_dt": {"type": "string", "format": "date"}
    },
    "oneOf": [
        {"required": ["start_dt"]},
        {"required": ["end_dt"]}
    ]
}

Online demos with your three examples:

  • OK
  • OK
  • NOT OK
like image 130
cloudfeet Avatar answered Sep 28 '22 01:09

cloudfeet