JSON 对象数组的架构定义

JSON Schema definition for array of objects

我看过这个other question,但不太一样,我觉得我的问题更简单,但就是没用。

我的数据如下所示:

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

我想在 Node.js 项目中使用 AJV 进行 JSON 验证,我尝试了几种模式来描述我的数据,但我总是得到这个作为错误:

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

我尝试过的架构如下所示:

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

我也曾尝试使用 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 生成模式,但这也给了我一个类似的错误:

Found 1 error(s)
 Message:
 Invalid type. Expected Array but got Object.
 Schema path:
 #/type

您已正确定义架构,只是它与您所说的正在验证的数据不匹配。如果您更改 属性 名称以匹配模式,您仍然有一个问题。如果你想让"toll"和"message"为null,你可以这样做

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

但是,这与您收到的错误消息无关。该消息意味着您正在验证的数据不是数组。您发布的示例数据不应导致此错误。您是 运行 某些数据的验证者,而不是问题中发布的数据?