Baumannzone
Baumannzone

Reputation: 780

JSON Schema - multiple types

I have this schema. It checks comments, and works fine at the moment.

var schema = {
  id: '',
  type: 'object',
  additionalProperties: false,
  properties: {
    text: {
      type: 'string',
      minLength: 1,
      required: true
    },
    author: {
      type: 'number',
      required: true
    }
  }
}; 

My comment structure is:

{
  text: "Hello world!",
  author: 1
}

But now, I need to validate an array of objects like this. So I can get something like:

  [
    {
      text: "Hello world! Im comment #1",
      author: 1
    },
    {
      text: "Super awesome comment #2!",
      author: 0
    }
  ]

Sometimes I get one comment only so I get one object, and need to use first schema, but sometimes I get an array of comments, and my schema does not fit.

I heard about json schema anyOf, but I dont know how to do it.

Some like:

anyOf  
   schema-1 (object)
   schema-2 (array with objects)

Any help?

Thanks.

Upvotes: 9

Views: 23383

Answers (1)

cloudfeet
cloudfeet

Reputation: 12901

The solution is to have a common definition in one place, and then reference that common definition from two different options inside oneOf:

Here, we put the simple object definition inside definitions:

{
    "definitions": {
        "singleObject": {
            ... same definition as in your question ...
        }
    }
}

We then reference this schema, inside oneOf:

{
    "oneOf": [
        {"$ref": "#/definitions/singleObject"}, // plain object
        {
            "type": "array", // array of plain objects
            "items": {"$ref": "#/definitions/singleObject"}
        }
    ],
    "definitions": {
        "singleObject": {...}
    }
}

You can organise this a few different ways - I personally often end up with the simple-object definition as the root schema, and have the single/array switcher in definitions, so the schema for my documents is actually http://example.com/schema#/definitions/arrayOrSingle.

Upvotes: 10

Related Questions