2013-05-31 88 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 –