Jeremy Gooch
Jeremy Gooch

Reputation: 1029

JSON Schema - array of different objects

I'd like to know how to specify a JSON schema for an array of different objects. This thread gives me half the answer, but fails when I have multiple instances of each type of object.

Here's a sample XML, based on the example given here but with the "Product" object being repeated:-

{
  "things": [
    {
      "entityType" : "Product",
      "name" : "Pepsi Cola",
      "brand" : "pepsi"
    },
    {
      "entityType" : "Product",
      "name" : "Coca Cola",
      "brand" : "coke"
    },
    {
      "entityType" : "Brand",
      "name" : "Pepsi Cola"
    }
  ]
}

The following schema will validate the above XML only when there is a single instance of each type (i.e. if "Product" only appears once).

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "https://schemas.example.com/things",
  "title": "Things",
  "description": "Some things",
  "type": "object",
  "required": [
    "things"
  ],
  "properties": {
    "things": {
      "type": "array",
      "items": [
        {
          "type": "object",
          "required": [
            "entityType",
            "name"
          ],
          "properties": {
            "entityType": {
              "type": "string",
              "enum": [
                "Product"
              ]
            },
            "name": {
              "type": "string"
            },
            "brand": {
              "type": "string"
            }
          }
        },
        {
          "type": "object",
          "required": [
            "entityType",
            "name"
          ],
          "properties": {
            "entityType": {
              "type": "string",
              "enum": [
                "Brand"
              ]
            },
            "name": {
              "type": "string"
            }
          }
        }
      ]
    }
  },
  "additionalProperties": false
}

To add to the entertainment, I can't use keywords like "AnyOf", as I'm embedding this schema into a Swagger 2.0 document, and those keywords aren't supported.

Thanks,

J.

Upvotes: 1

Views: 2940

Answers (1)

Jason Desrosiers
Jason Desrosiers

Reputation: 24489

Without anyOf you're out of luck. The best you can do is use one schema that covers all of the options. It not a great solution, but it's better than nothing.

Upvotes: 2

Related Questions