【问题标题】:JSON Schema Requirement EnforcementJSON Schema 要求执行
【发布时间】:2014-07-07 22:11:33
【问题描述】:

所以这是我第一次使用 JSON Schema,我有一个关于需求的相当基本的问题。

我的顶级架构如下:

schema.json:

{
    "id": "http://localhost/srv/schemas/schema.json",
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "properties": {
        "event": { "$ref": "events_schema.json#" },
        "building": { "$ref": "buildings_schema.json#" }
    },
    "required": [ "event" ],
    "additionalProperties": false
}

我还有另外两个包含对象字段定义的架构定义文件(events_schema.json 和 building_schema.json)。特别感兴趣的是buildings_schema.json。

buildings_schema.json:

{
    "id": "http://localhost/srv/schemas/buildings_schema.json",
    "$schema": "http://json-schema.org/draft-04/schema#",
    "description": "buildings table validation definition",
    "type": "object",
    "properties": {
        "BuildingID": {
            "type": "integer",
            "minimum": 1
        },
        "BuildingDescription": {
            "type": "string",
            "maxLength": 255
        }
    },
    "required": [ "BuildingID" ],
    "additionalProperties": false
}

我正在使用这个文件来测试我的验证:

test.json:

{
    "event": {
        "EventID": 1,
        "EventDescription": "Some description",
        "EventTitle": "Test title",
        "EventStatus": 2,
        "EventPriority": 1,
        "Date": "2007-05-05 12:13:45"
    },
    "building": {
        "BuildingID": 1,
    }
}

通过验证很好。但是当我使用以下内容时:

test2.json

{
    "event": {
        "EventID": 1,
        "EventDescription": "Some description",
        "EventTitle": "Test title",
        "EventStatus": 2,
        "EventPriority": 1,
        "Date": "2007-05-05 12:13:45"
    }
}

我收到错误:[building] the property BuildingID is required

在我的 building_schema.json 文件中,我有 "required": [ "BuildingID" ] 行,这就是导致错误的原因。似乎 schema.json 正在遍历属性定义并执行所有要求。这是违反直觉的,我希望它仅在强制执行父属性时才强制执行要求。

我有几种方法可以解决这个问题,包括数组和从根本上改变 JSON 的结构,但这违背了我尝试验证现有 JSON 的目的。我已阅读文档 (/sigh) 并没有发现与此问题相关的任何内容。我缺少一些简单的需求继承设置吗?

我在此处使用 Json-Schema 进行 PHP 实现:https://github.com/justinrainbow/json-schema

【问题讨论】:

  • 问题可能出在您引用模式的方式上。您是否尝试将 schema、buildings_schema 和 events_schema 的定义与相关 refs 放在同一个文件中?也许我们可以确定问题出在哪里,或者在文件解析和架构层次结构中,或者在验证器本身中。

标签: php json jsonschema


【解决方案1】:

在与不同的验证器搞乱之后,这似乎是验证器的问题。验证器通过引用假定所需的继承。我通过简单地将主模式分解为子模式并仅在必要时使用所需的子模式来解决此问题。

【讨论】:

    猜你喜欢
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 2019-04-23
    • 2017-05-10
    • 2015-09-01
    • 1970-01-01
    相关资源
    最近更新 更多