2013-05-31 65 views
2

我有多種模式,分別爲數據子類型:Python Validictory(JSON模式驗證):如何OR多個模式?

type_one = { 
    "type": "object", 
    "properties": { 
    "one": "string" 
    } 
} 

type_two = { 
    "type": "object", 
    "properties": { 
    "one": "string", 
    "two": "string" 
    } 
} 

我要的是檢查,如果輸入的數據是「type_one」 OR「type_two」或拋出一個錯誤。事情是這樣的:

general_type = { 
    "type": [type_one, type_two] 
} 

我進來的數據是這樣的:

{ 
    "one": "blablabla", 
    "two": "blebleble", 
    ... 
} 

我一直在測試多種方法,但沒有成功...任何想法? Thx

回答

4

您可以在對象模式中使用屬性"additionalProperties": False只允許一組精確的鍵。

首先,讓我們擁有有效的模式結構:

type_one = { 
    "type": "object", 
    "additionalProperties": False, 
    "properties": { 
     "one": {"type": "string"} 
    } 
} 

type_two = { 
    "type": "object", 
    "additionalProperties": False, 
    "properties": { 
     "one": {"type": "string"}, 
     "two": {"type": "string"} 
    } 
} 

general_type = { 
    "type": [type_one, type_two] 
} 

注:從你的問題的模式爲"one": "string",它應該是"one": {"type": "string"}

這裏是我們輸入數據:

data_one = { 
    "one": "blablabla" 
} 

data_two = { 
    "one": "blablabla", 
    "two": "blablabla" 
} 

這裏是驗證:

import validictory 

# additional property 'two' not defined by 'properties' are not allowed 
validictory.validate(data_two, type_one) 

# Required field 'two' is missing 
validictory.validate(data_one, type_two) 

# All valid 
validictory.validate(data_one, type_one) 
validictory.validate(data_two, type_two) 

validictory.validate(data_one, general_type) 
validictory.validate(data_two, general_type) 

我希望這有助於。

+0

不錯!非常感謝!只需鏈接到您的Validictory教程http://www.alexconrad.org/2011/10/json-validation.html –