JSON Schema definition for array of objects

99封情书 提交于 2019-12-03 11:03:47

问题


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

回答1:


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?



来源:https://stackoverflow.com/questions/36757949/json-schema-definition-for-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!