Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

False positives for an incorrectly constructed schema for an array of objects #258

Open
stephendisalvio opened this issue Jul 12, 2017 · 1 comment

Comments

@stephendisalvio
Copy link

Say my response is a JSON array of objects:

{
  all_my_objects: [
    {
       "id": 1
       "name": "name"
    },
    ...
  ]
}

If I (incorrectly) build my schema like this:

var schema = {,
  schema: "http://json-schema/draft-04/schema#",
  description: "description",
  type: "array",
  items: {,
    id: {,
      type: "string"
    },
    name: {,
      type: "number"
    },
  },
};
response = JSON.parse(responseBody);
tv4.validate(response, schema);

Validation will pass although id should expect a number and name should expect a string.
The solution is to add a "properties" key below items like so:

var schema = {,
  schema: "http://json-schema/draft-04/schema#",
  description: "description",
  type: "array",
  items: {,
    properties {,
      id: {,
        type: "string"
      },
      name: {,
        type: "number"
      },
    },
  },
};

This now fails as expected. I don't know if the non-failure in the first case is a bug or expected behavior, but I am wondering why it doesn't fail, when it clearly is an incorrectly constructed schema. It doesn't appear as if tv4 is trying to validate that those items are in the array, or that the syntax is incorrect, or any other error one might expect.

@Miista
Copy link

Miista commented Jul 27, 2017

I had the same problem as you, but I have come to the conclusion that it is by design.

When using the items key, you "starts" a new schema so to speak. Might be the wrong terminology.

In the schema for an array, you must specify the type of items the array may contain. The type of an item is itself a schema. In other words, the value for the items key must be a schema itself.
See below.

type: "object",
properties: { ... }

versus

type: "array",
items: {
    <some schema>
}

This is why validation still occurs. Your example:

items: {,
    id: {,
        type: "string"
    },
    name: {,
        type: "number"
    },
}

translates to the following valid schema:

{}

But when you stick it into a properties key, Tiny Validator knows where to find the properties to be validated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants