JSON Schema 验证:验证对象数组

dj_*_*ssi 3 php validation schema json jsonschema

我开始关注 JSON 并想对其进行验证。

[
    {
        "remindAt": "2015-08-23T18:53:00+02:00",
        "comment": "Postman Comment"
    },
    {
        "remindAt": "2015-08-24T18:53:00+02:00",
        "comment": "Postman Comment"
    }
]
Run Code Online (Sandbox Code Playgroud)

我的架构目前看起来如下

{
    "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"
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

提前致谢

jru*_*ren 6

您的架构中有一些错误。首先,您正在使用数组对象的属性properties是对象的子句,而不是数组,因此将被忽略。

json-schema v4 开始所需的是一个数组。

以下架构将需要数组中所有项目的提醒和注释属性:

{
    "type": "array",
    "items": {
        "additionalProperties": false,
        "properties": {
            "remindAt": {
                "type": "string",
                "format": "date-time"
            },
            "comment": {
                "type": "string"
            }
        },
        "required": ["remindAt", "comment"]
    }
}
Run Code Online (Sandbox Code Playgroud)