【问题标题】:Json schema for array of objects doesn't validate对象数组的 Json 模式未验证
【发布时间】:2016-09-22 07:48:07
【问题描述】:

我有这个用于 json 响应的架构

{
    "title": "Products",
    "description": "schema for products",
    "type": "array",
    "properties": {
        "id": {
            "description": "id of a product",
            "type": "integer"
        },
        "name": {
            "description": "name of the product",
            "type": "string"
        },
        "created_at": {
            "description": "record created_at",
            "type": "string",
            "format": "date-time"
        },
        "updated_at": {
            "description": "record updated_at",
            "type": "string",
            "format": "date-time"
        }
    },
    "required": ["id", "name"]
}

我想将此架构与此 json 匹配

[{
    "id": 1,
    "name": "Cricket Ball"
}, {
    "id": 2,
    "name": "Soccer Ball"
}, {
    "id": 3,
    "name": "football ball"
}, {
    "id": 4,
    "name": "Basketball ball"
}, {
    "id": 5,
    "name": "Table Tennis ball"
}, {
    "id": 6,
    "name": "Tennis ball"
}]

此架构与响应匹配,但它也与必填字段为 this 的架构匹配

"required": ["ids", "names"]

我认为架构已针对数组进行验证,而数组中的对象未经过验证。

【问题讨论】:

  • 不清楚您实际在做什么。包括控制器和视图(如果您使用 jbuilder)或序列化程序(如果您使用 AMS)。
  • 这与 Rails 无关。在最近的编辑中删除了 rails 标签

标签: arrays json jsonschema


【解决方案1】:

按照您现在设置的方式,您的 properties 键是指数组本身,而不是每个项目,并且被忽略(因为数组没有属性,它们只有项目)。您需要使用items 键来验证数组中的每个项目,如下所示:

{
    "title": "Products",
    "description": "schema for products",
    "type": "array",
    "items": {
      "type": "object",
      "properties": {
        "id": {
            "description": "id of a product",
            "type": "integer"
        },
        "name": {
            "description": "name of the product",
            "type": "string"
        },
        "created_at": {
            "description": "record created_at",
            "type": "string",
            "format": "date-time"
        },
        "updated_at": {
            "description": "record updated_at",
            "type": "string",
            "format": "date-time"
        }
      },
      "required": ["id", "name"]
    }
}

【讨论】:

  • PS json scheme validator 是现场测试模式的好方法。
  • 做到了。真棒
  • 我尝试了the schema validator,但故意更改示例 JSON 数据数组中的 第二个对象,将“id”更改为“id2”,但页面显示“未发现错误”。我们如何让验证器也验证第二个、第三个、第四个等对象?
  • 为什么以下 json 没有针对您的架构给出验证错误? [{ "id": "1", "name": 2 }, { "id": "3" }]
【解决方案2】:

试试map

new_array = response.map{ |k| { 'id': k['properties']['id']['description'], 'name': k['properties']['name']['description'] } }

【讨论】:

  • 对不起,这不是我问的。我不希望将第一个转换为第二个。我要匹配json-schema
猜你喜欢
  • 2020-10-31
  • 2020-07-28
  • 2018-09-20
  • 2017-10-23
  • 2015-10-24
  • 1970-01-01
  • 2018-02-23
  • 2021-05-18
  • 2020-03-29
相关资源
最近更新 更多