doukuipai8544
doukuipai8544
2015-08-02 09:42
浏览 441

JSON Schema验证:验证对象数组

I get following JSON and would like to validate it.

[
    {
        "remindAt": "2015-08-23T18:53:00+02:00",
        "comment": "Postman Comment"
    },
    {
        "remindAt": "2015-08-24T18:53:00+02:00",
        "comment": "Postman Comment"
    }
]

My schema looks currently as following

{
    "type": "array",
    "required": true,
    "properties": {
        "type": "object",
        "required": false,
        "additionalProperties": false,
        "properties": {
            "remindAt": {
                "required": true,
                "type": "string",
                "format": "date-time"
            },
            "comment": {
                "required": true,
                "type": "string"
            }
        }
    }
}

This is not working. It validates to true even if I remove comment from JSON ddata. I guess structure of my schema file is wrong.

For validating I use following library https://packagist.org/packages/justinrainbow/json-schema

Can please someone explain to me what I do wrong and how I properly validate given JSON data?

Thanks in advance

图片转代码服务由CSDN问答提供 功能建议

我得到了JSON并希望对其进行验证。

  [
 {
“remindAt”:“2015-08-23T18:53:00 + 02:00”,
“评论”:“邮递员评论”
},
 {
“remindAt”:  “2015-08-24T18:53:00 + 02:00”,
“评论”:“邮差评论”
} 
] 
   
 
 

我的 schema目前看起来如下

  {
“type”:“array”,
“required”:true,
“properties”:{
“type”  :“object”,
“required”:false,
“additionalProperties”:false,
“properties”:{
“remindAt”:{
“required”:true,
“type”:“  string“,
”format“:”date-time“
},
”comment“:{
”required“:true,
”type“:”string“
} 
} 
 
  } 
} 
   
 
 

这不起作用。 即使我从JSON ddata中删除注释,它也会验证为true。 我猜我的架构文件的结构是错误的。

为验证我使用以下库 https:// packagist.org/packages/justinrainbow/json-schema

请有人向我解释我做错了什么以及如何正确验证给定的JSON数据?

提前致谢

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douyujun0152
    douyujun0152 2015-08-03 06:20
    已采纳

    There are some errors in your schema. First, you are using properties for an array object. properties is a clause for objects, not arrays, so it will be ignored.

    From json-schema v4, required is an array.

    The following schema will require remindAt and comment properties for all items in the array:

    {
        "type": "array",
        "items": {
            "additionalProperties": false,
            "properties": {
                "remindAt": {
                    "type": "string",
                    "format": "date-time"
                },
                "comment": {
                    "type": "string"
                }
            },
            "required": ["remindAt", "comment"]
        }
    }
    
    点赞 评论

相关推荐