【问题标题】:JSON Schema definition for array of objects对象数组的 JSON 模式定义
【发布时间】:2016-08-13 23:12:28
【问题描述】:

我见过这个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 生成架构,但这也不起作用,为了验证应该输出正确的结果,我尝试根据jsonschemavalidator.net 验证该输出,但这也给我一个类似的错误:

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

【问题讨论】:

    标签: json jsonschema json-schema-validator


    【解决方案1】:

    您已正确定义架构,但它与您所说的正在验证的数据不匹配。如果您更改属性名称以匹配架构,您仍然会遇到一个问题。如果要允许“toll”和“message”为空,可以执行以下操作。

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

    但是,这与您收到的错误消息无关。该消息意味着您正在验证的数据不是数组。您发布的示例数据不应导致此错误。您是否在问题中发布的数据之外的其他数据上运行验证器?

    【讨论】:

    • 我什至还没到验证数据的地步,现在我只是想验证架构本身。
    • @KyleFalconer,您的架构有效。我尝试了您链接到的验证器。我认为您遇到的问题是它默认将{} 放在“输入 JSON”字段中。您需要将其更改为数组。该工具使错误看起来与架构有关,但实际上是数据无效。
    • 这对我有用,包括所需的密钥。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-08-19
    • 2020-02-09
    • 1970-01-01
    • 2018-09-17
    • 1970-01-01
    • 2019-03-11
    • 2016-09-02
    • 2013-10-22
    相关资源
    最近更新 更多