json模式定义帮助程序
schemabuilder的Python项目详细描述
帮助您为验证或发布定义json模式。
要求
它需要python 2.7和jsonschema。jsonschema或setuptools 应该与python一起安装。
安装
使用pip:
pip install schemabuilder
或简易安装:
easty_install schemabuilder
您可以手动安装:
git clone https://github.com/dinoboff/schemabuilder.git cd schemabuilder python setup.py install
用法
原语
json模式原语由以下类型的对象表示:
- schemabuilder.Str
- schemabuilder.Bool
- schemabuilder.Number
- schemabuilder.Int
- schemabuilder.Object
- schemabuilder.Array
>>>importschemabuilderasjsb>>>importpprint>>>>>>name=jsb.Str(pattern="^[a-zA-Z][- 'a-zA-Z0-9]+")>>>email=jsb.Str(format="email")>>>user=jsb.Object(properties={...'name':name(required=True),...'email':email(),...'home':jsb.Str(format='uri'),...})>>>pprint.pprint(user.to_dict()){'properties':{'email':{'type':'string'},'home':{'format':'uri','type':'string'},'name':{'type':'string'}},'required':['name'],'type':'object'}
模式
schema收集这些定义进行验证(使用jsonschema)或 出版。
>>>importschemabuilderasjsb>>>importpprint>>>>>>my_schemas=jsb.Schema(id='http://example.com/schemas.json#')>>>name=my_schemas.define(...'name',jsb.Str(pattern="^[a-zA-Z][- 'a-zA-Z0-9]+")...)>>>email=my_schemas.define('email',jsb.Str(format="email"))>>>user=my_schemas.define('user',jsb.Object(properties={...'name':name(required=True),...'email':email(required=True),...}))>>>>>>user.validate({'name':'bob'})Traceback(mostrecentcalllast):File"<stdin>",line1,in<module>File"schemabuilder/schema.py",line50,invalidatevalidator.validate(data)File"/Users/bob/pyenv/lib/python2.7/site-packages/jsonschema/validators.py",line117,invalidateraiseerrorjsonschema.exceptions.ValidationError:'email'isarequiredpropertyFailedvalidating'required'inschema:{'properties':{'email':{'$ref':'#/definitions/email'},'name':{'$ref':'#/definitions/name'}},'required':['name','email'],'type':'object'}Oninstance:{'name':'bob'}>>>>>>user.validate({'name':'bob','email':'bob@example.com'})>>>>>>importjson>>>printjson.dumps(my_schemas.to_dict(),indent=4){"definitions":{"email":{"type":"string","format":"email"},"user":{"required":["name","email"],"type":"object","properties":{"name":{"$ref":"#/definitions/name"},"email":{"$ref":"#/definitions/email"}}},"name":{"pattern":"^[a-zA-Z][- 'a-zA-Z0-9]+","type":"string"}},"id":"http://example.com/schemas.json#","$schema":"http://json-schema.org/draft-04/schema#"}