vjson创建一个对象来序列化jsonschema中指定的唯一类型。它的工作方式类似于json模块。
vjson的Python项目详细描述
vjson
0.1.0
vjson创建一个对象来序列化jsonschema中指定的唯一类型。它的工作方式类似于json模块。
安装
接下来,执行命令。:
$ pip install vjson
如何使用
使用jsonschema定义对象。:
>>> import vjson >>> _json = vjson.ValidatedJSON({ ... 'type': 'object', ... 'properties': { ... 'price': {'type': 'number'}, ... 'name': {'type': 'string'}, ... }, ... })
此对象可以转储/loads()/dump()/load()可序列化对象,如在JSON模块中一样。:
>>> _json.loads('{"name" : "Eggs", "price" : 34.99}') {'name': 'Eggs', 'price': 34.99} >>> _json.dumps({"name": "Eggs", "price": 34.99}) '{"name": "Eggs", "price": 34.99}'
如果试图传递违反构造函数中指定的jsonschema的数据,则会引发一个vjson.jsonvalidationerror.:
>>> _json.loads('{"name" : "Eggs", "price" : "34.99"}') Traceback (most recent call last): File "/tmp/test/var/src/develop/vjson/src/vjson/__init__.py", line 32, in _wrap jsonschema.validate(data, schema) File "/tmp/test/env/lib/python3.4/site-packages/jsonschema/validators.py", line 478, in validate cls(schema, *args, **kwargs).validate(instance) File "/tmp/test/env/lib/python3.4/site-packages/jsonschema/validators.py", line 123, in validate raise error jsonschema.exceptions.ValidationError: '34.99' is not of type 'number' Failed validating 'type' in schema['properties']['price']: {'type': 'number'} On instance['price']: '34.99' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/tmp/test/var/src/develop/vjson/src/vjson/__init__.py", line 34, in _wrap raise JSONValidationError(err) vjson.JSONValidationError: '34.99' is not of type 'number' Failed validating 'type' in schema['properties']['price']: {'type': 'number'} On instance['price']: '34.99' >>>