2015-06-02 32 views
0

是否有可能強制已知對象(「敵人」和「朋友」)被定義而其他對象被允許?未來證明JSON模式

我已經添加了最後一個對象{「type」:「object」}來顯示預期的行爲 - 但實際上最後一個對象會否定導致任何類型的兩個定義對象(「敵人」和「朋友」)的對象對此模式有效。如果我刪除最後一個對象,它將允許這兩個對象,但沒有別的。

JSON模式(使用更快的測試陣列):

{ 
    "type": "array", 
    "items": { 
    "anyOf": [ 
     {"$ref": "#/definitions/friend"}, 
     {"$ref": "#/definitions/enemy"}, 
     {"$ref": "#/definitions/future"} 
    ] 
    }, 
    "definitions": { 

    "friend": { 
     "type": "object", 
     "properties": { 
     "time": {"type": "string"}, 
     "value": {"type": "number", "minimum": 100} 
     }, 
     "required": ["time", "value"], 
     "additionalProperties": false 
    }, 

    "enemy": { 
     "type": "object", 
     "properties": { 
     "enemy": {"type": "string"}, 
     "color": {"type": "number"} 
     }, 
     "required": ["enemy", "color"], 
     "additionalProperties": false 
    }, 

    "future": { 
     "type": "object", 
     "properties": { 
     "time": {"type": "string"} 
     }, "required": ["time"], 
     "additionalProperties": true 
    } 

    } 
} 

例JSON(前3名應該是OK,最後3不應該OK):

[ 
    {"time": "123", "value": 100}, <- should be valid 
    {"time": "1212", "value": 150}, <- should be valid 
    {"enemy": "bla", "color": 123}, <- should be valid 
    {"time": "1212", "value": 50}, <- should be invalid bcoz of "future" 
    {"enemy": "bla", "color": "123"}, <- shouldn't be valid bcoz of "enemy" schema 
    {"somethingInFuture": 123, "someFutProp": "ok"} <- should be valid 
] 
+0

您能否提供您想要考慮有效的示例數據以及哪些數據不是?我相信'依賴關係'可以在那裏幫助你 – fge

+0

不需要依賴關係,只是讓它變得更復雜我認爲。 – MrUs

回答

0

這不是很清楚什麼你真的想要,但你可能想在這裏使用dependenciesminProperties的組合。這裏使用這個關鍵字的兩種形式:屬性依賴和模式依賴。您還希望至少定義一個屬性,因此minProperties。所以,你可以做這樣的事情(請注意,我也工廠化共同架構color;它可能會,也可能不會,是你想要的):

{ 
    "type": "object", 
    "minProperties": 1, 
    "additionalProperties": { 
     "type": "string" // All properties not explicitly defined are strings 
    }, 
    "properties": { 
     "color": { "type": "number" } 
    }, 
    "dependencies": { 
     "enemy": "color", // property dependency 
     "friend": { // schema dependency 
      "properties": { "color": { "minimum": 50 } }, 
      "required": [ "color" ] 
     } 
    } 
} 

注意,該模式仍允許「敵人」和「朋友「(同樣是你的原始模式)。爲了做得更好,應該提供想要認爲有效和無效的JSON。