How to represent sum/union types in in json schema

2019-03-25 16:56发布

问题:

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?

回答1:

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