69

I've seen this other question but it's not quite the same, and I feel like my issue is simpler, but just isn't working.

My data would look like this:

[
    { "loc": "a value 1", "toll" : null, "message" : "message is sometimes null"},
    { "loc": "a value 2", "toll" : "toll is sometimes null", "message" : null}
]

I'm wanting to use AJV for JSON validation in a Node.js project and I've tried several schemas to try to describe my data, but I always get this as the error:

[ { keyword: 'type',
    dataPath: '',
    schemaPath: '#/type',
    params: { type: 'array' },
    message: 'should be array' } ]

The schema I've tried looks like this:

{
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "loc": {
        "type": "string"
      },
      "toll": {
        "type": "string"
      },
      "message": {
        "type": "string"
      }
    },
    "required": [
      "loc"
    ]
  }
}

I've also tried to generate the schema using this online tool but that also doesn't work, and to verify that that should output the correct result, I've tried validating that output against jsonschemavalidator.net, but that also gives me a similar error:

Found 1 error(s)
 Message:
 Invalid type. Expected Array but got Object.
 Schema path:
 #/type
Community
  • 1
  • 1
Kyle Falconer
  • 8,302
  • 6
  • 48
  • 68

1 Answers1

118

You have defined your schema correctly, except that it doesn't match the data you say you are validating. If you change the property names to match the schema, you still have one issue. If you want to allow "toll" and "message" to be null, you can do the following.

{
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "loc": {
        "type": "string"
      },
      "toll": {
        "type": ["string", "null"]
      },
      "message": {
        "type": ["string", "null"]
      }
    },
    "required": [
      "loc"
    ]
  }
}

However, that isn't related to the error message you are getting. That message means that data you are validating is not an array. The example data you posted should not result in this error. Are you running the validator on some data other than what is posted in the question?

Jason Desrosiers
  • 22,479
  • 5
  • 47
  • 53
  • I'm not even to the point of validating against data, right now I'm only trying to validate the schema itself. – Kyle Falconer Apr 21 '16 at 02:07
  • 1
    @KyleFalconer, your schema is valid. I tried the validator you linked to. I think the problem you are having is that it puts `{}` in the "Input JSON" field by default. You need to change that to an array. The tool makes it look like the error is with the schema, but it is actually the data that is invalid. – Jason Desrosiers Apr 21 '16 at 02:16
  • This worked for me, including the required keys. Thank you! – Aqeeb Imtiaz Harun Nov 05 '21 at 14:42
  • How would you validate if the different objects must have different constant values? – Petar Vasilev Jan 10 '22 at 12:55