Correct JSON Schema for an array of items of different type

deepwinter picture deepwinter · Mar 13, 2013 · Viewed 44k times · Source

I have an unordered array of JSON items. According to the specification http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.5 the json schema below will only validate if the objects in the array appear IN THAT ORDER. I don't want to specify an order, just validate the objects within the array, regardless of order or number of objects. From the spec I can't seem to understand how this is done.

"transactions" : {
    "type" : "array",
    "items" : [
        {
            "type" : "object",
            "properties" : {
                "type" : {
                    "type" : "string",
                    "enum" : ["BUILD", "REASSIGN"]
                }
            }
        },
        {
            "type" : "object",
            "properties" : {
                "type" : {
                    "type" : "string",
                    "enum" : ["BREAK"]
                }
            }
        }
    ]
}

Answer

deepwinter picture deepwinter · Mar 28, 2013

I asked this same question on the JSON schema google group, and it was answered quickly. User fge asked that I post his response here:

Hello,

The current specification is draft v4, not draft v3. More specifically, the validation specification is here:

http://tools.ietf.org/html/draft-fge-json-schema-validation-00

The web site is not up to date, I don't know why... I'll submit a pull request.

With draft v4 you can use this:

{
    "type": "array",
    "items": {
        "oneOf": [
            {"first": [ "schema", "here" ] }, 
            {"other": [ "schema": "here" ] }
        ]
    }  
}

For instance, this is a schema for an array where items can be either strings or integers (it can be written in a more simple way though):

{
    "type": "array",
    "items": {
        "oneOf": [
            {"type": "string"},
            {"type": "integer"}
        ]
    }
}

This is the correct answer. My corrected schema now includes:

"transactions" : {
    "type" : "array",
    "items" : {
        "oneOf" : [
            {
                "type" : "object",
                "properties" : {
                    "type" : {
                        "type" : "string",
                        "enum" : ["BUILD", "REASSIGN"]
                    }
                }
            },
            {
               "type" : "object",
               "properties" : {
                 "type" : {
                   "type" : "string",
                   "enum" : ["BREAK"]
                  }
               }
            }
        ]
    }
}