2014-07-07 160 views
0

所以这是我第一次使用JSON模式,并且我有一个关于需求的基本问题。JSON模式要求执行

我的顶层架构如下:

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和buildings_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

里面我buildings_schema.json文件我也行"required": [ "BuildingID" ]这是什么原因造成的错误。看起来,schema.json正在遍历属性定义并强制执行所有要求。这是违反直觉的,我希望它只在执行父属性时才强制执行一项要求。

我有几种解决这个问题的方法,它涉及到数组并且从根本上改变了JSON的结构,但是这种方式挫败了我尝试验证现有JSON的目的。我已经阅读了文档(/叹气),并没有发现任何有关这个问题。是否有一个简单的要求继承设置我缺少?

我使用JSON-模式的PHP实现从这里:https://github.com/justinrainbow/json-schema

+0

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

回答

0

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