krg7880 / json-schema-generator

Generates draft v4 schema from a local file or a remote JSON url.
MIT License
174 stars 53 forks source link

schema generated for an empty array is invalid #20

Open brendonjohn opened 7 years ago

brendonjohn commented 7 years ago
const gen = require('json-schema-generator')
const testObj = {test: []}
const schema = gen(testObj)
console.log(schema)

This outputs:

{ '$schema': 'http://json-schema.org/draft-04/schema#',
  description: '',
  type: 'object',
  properties: 
   { test: 
      { type: 'array',
        uniqueItems: undefined,
        minItems: undefined,
        items: [Object] } },
  required: [ 'test' ] }

This is problematic as the value of minItems inside schema.properties.test is undefined, so when the original object is tested against the generated schema, we have a validation error.

var Validator = require('jsonschema').Validator
const validator = new Validator()
const result = validator.validate(testObj, schema, {throwError: false})

result.errors contains:

[ ValidationError {
    property: 'instance.test',
    message: 'does not meet minimum length of undefined',
    schema: 
     { type: 'array',
       uniqueItems: undefined,
       minItems: undefined,
       items: [Object] },
    instance: [],
    name: 'minItems',
    argument: undefined,
    stack: 'instance.test does not meet minimum length of undefined' } ]