voxpupuli / json-schema

Ruby JSON Schema Validator
MIT License
1.53k stars 242 forks source link

Empty array (incorrectly?) triggering ValidationError #311

Closed jnardone closed 8 years ago

jnardone commented 8 years ago

I am trying to validate a schema which should have a required key but may either have a populated array (of objects!) OR an empty array. (Using 2.6.0)

Here's my simple repro case. Schema first. Note that my array, if it had elements, would be an array of objects and not simple elements.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "x": {
      "type": "array",
      "items": [
        {
          "type": "object",
          "properties": {
            "a": {
              "type": "string"
            }
          },
          "required": ["a"],
          "additionalProperties": false
        }
      ]
    }  
  },
  "required": [ "x" ],
  "additionalProperties": false
}

The populated case succeeds: {"x": [ {"a":"foo"} ] }

However, the empty array case of {"x": [] }' fails with JSON::Schema::ValidationError: The property '#/x/0' of type NilClass did not match the following type: object in schema file:///zzz/schemas/schema.json from /zzz/vendor/bundle/ruby/2.3.0/gems/json-schema-2.6.0/lib/json-schema/attribute.rb:18:in `validation_error'

Am I making a fundamental error with my schema, or is this a bug? I'm new at this but the way I read the spec, the empty array should be allowed in this case...

jnardone commented 8 years ago

Ok, I'm still learning here. I think my solution is to define the inner array as allowing both object and null as choices, e.g.

    "x": {
      "type": "array",
      "items": [
        {
          "type": ["object", "null"],

though I wouldn't mind someone validating that...

RST-J commented 8 years ago

The problem is that you specified the array items within an array, you need to specify it in an object. Specifying an object schema here means that all of the 0..n elements within the array must adhere to the given schema (no element is always valid to any schema). But if you specify an array of schemas, the elements at the respective index position must adhere to the schema at the same position. http://json-schema.org/latest/json-schema-validation.html#anchor36

jnardone commented 8 years ago

Oh, I see! Thanks!