philou
philou

Reputation: 383

json schema: Can we use "items" within an "object"

The keyword "items" seems to be associated with "array" in most json schema examples I ve seen. However I tried using it with an object using this useful tool: http://www.jsonschemavalidator.net/ (JSON Schema Draft 4) and it works. I can t find any documentation stating that this is legal although it feels right to me.

"value": { 
      "type": "object",
      "items": ...
}

Is this really legal?

Upvotes: 0

Views: 151

Answers (1)

Jason Desrosiers
Jason Desrosiers

Reputation: 24439

Here is the documentation you are looking for.

Some validation keywords only apply to one or more primitive types. When the primitive type of the instance cannot be validated by a given keyword, validation for this keyword and instance SHOULD succeed.

To illustrate the concept, take this schema as an example.

{
  "items": { "type": "string" },
  "maxLength": 2,
  "required": ["foo"]
}

["foo"] validates

  • items -> pass
  • maxLength -> ignored
  • required -> ignored

{ "foo": "bar" } validates

  • items -> ignored
  • maxLength -> ignored
  • required -> pass

"foo" does not validate

  • items -> ignored
  • maxLength -> fail
  • required -> ignored

3 validates

  • items -> ignored
  • maxLength -> ignored
  • required -> ignored

Although it is possible to write schemas this way, it is recommended to not mix type keywords within a single schema. You get more readable schemas using anyOf instead.

{
  "anyOf": [
    {
      "type": "string",
      "maxLength": 2
    },
    {
      "type": "array",
      "items": { "type": "string" }
    },
    {
      "type": "object",
      "required": "foo"
    }
  ]
}

Upvotes: 1

Related Questions