JSON Schema for Python
30 July 2008Ian Lewis has released a initial version of a JSON Schema validator for Python:
The source package can be downloaded here , and the documentation can be viewed here .
For installation instructions please read the included README file but for the restless, installation is done with the normal "python setup.py install" It is programmed in pure python so it should work in Appengine and the like and be easily installable on hosted machines.
You can use jsonschema to validate JSON documents like so, parsing a simple JSON document:
>>> import jsonschema
>>> jsonschema.validate("simplejson", {"type":"string"})Parsing a more complex JSON document:
>>> import simplejson
>>> import jsonschema
>>>
>>> data = simplejson.loads(’["foo", {"bar":["baz", null, 1.0, 2]}]’)
>>> schema = {
… "type":"array",
… "items":[
... {"type":"string"},
... {"type":"object",
... "properties":{
... "bar":{
... "items":[
... {"type":"string"},
... {"type":"any"},
... {"type":"number"},
... {"type":"integer"}
... ]
… }
… }
… }
… ]
… }
>>> jsonschema.validate(data,schema)Handling validation errors
ValueErrors are thrown when validation errors occur.>>> import jsonschema
>>> try:
… jsonschema.validate("simplejson", {"type":"string","minLength":15})
… except ValueError, e:
… print e.message
…
Length of ’simplejson’ must be more than 15.000000The jsonschema module supports a number of ways to extend validation
to user defined parameters and provides ways to override the default
validation. Please see the samples in the examples directory.
No comments yet