2014-07-07 74 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

不同的驗證搞亂後,它似乎是驗證的問題。驗證器通過引用來承擔所需的繼承。我通過簡單地將主模式拆分爲子模板並在必要時僅使用所需的子模板來解決此問題。