Validator for JSON/YML/DITC data
dictspec的Python项目详细描述
dictspec是一个简单的python库,用于验证基于字典和列表的数据结构。 您可以使用它根据自己的规范验证json/yaml文档。
它是麻省理工学院授权的,并且使用相对导入,所以你可以直接将它放入你的项目中。
示例
针对普通python数据对象或类型进行验证:
>>> spec = { ... 'foo': 1, ... 'bar': [basestring], ... } >>> data = { ... 'foo': 4, ... 'bar': ['hello', u'w\x00F6rld']} ... } >>> from dictspec.validator import validate >>> validate(spec, data)
使用更复杂的规格并获取详细错误:
>>> from dictspec.spec import number, required >>> spec = { ... required('foo'): number(), ... 'bar': bool(), ... } >>> data = { ... # missing 'foo' key ... 'bar': 4, # wrong type ... 'baz': True, # unknown key ... }>>> from dictspec.validator import ValidationError >>> try: ... validate(spec, data) ... except ValidationError, ex: ... print ex.errors ["missing 'foo' not in .", "unknown 'baz' in .", '4 in bar not of type bool']
还有递归和任意键:
>>> from dictspec.spec import anything, recursive >>> spec = { ... 'hello': recursive({ ... anything(): recursive(), ... }) ... } >>> data = { ... 'hello': {'any': {'thing': {'recursive':{}}}} ... } >>> validate(spec, data)