Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent sum/union types in in json schema

I am trying to document an existing use of JSON using json-schema. The system permits the following two possabilities for one of the object attributes.

Either

{
    "tracking_number" : 123
}

Or

{
    "tracking_number" : [ 123, 124, 125 ]
}

How can I express this using json schema?

like image 238
Q the Platypus Avatar asked Feb 17 '16 07:02

Q the Platypus


People also ask

What is Union in JSON?

to JSON Schema. Tagged union is a way to define a data type that can have different but rigid structure for different purposes. It is useful e.g. in command lists to devices, and event reports from devices.

What does allOf mean 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.

Does JSON support inheritance?

Inheritance in JSON: allOfThe inheritance is achieved in JSON by the keyword allOf. This keyword validates the value against all the subschemas. In the sub class definition, we would put the reference to the base type first followed by the new properties in the sub class.


1 Answers

Use anyOf to assert that the property must conform to one or another schema.

{
    "type": "object",
    "properties": {
        "tracking_number": {
            "anyOf": [
                { "$ref": "#/definitions/tracking_number" },
                { "type": "array", "items": { "$ref": "#/definitions/tracking_number" }
            ]
    },
    "definitions": {
        "tracking_number": { "type": "integer" }
    }
}
like image 60
Jason Desrosiers Avatar answered Oct 17 '22 03:10

Jason Desrosiers