As we work with Python and JSON-Schema, we found the necessity to create JSON-Schemas from Python classes, but we didn’t find any existing libraries to make this task easier, so we wrote one :)
Py2JSON is a library that will create from a given Python class a JSON-Schema string that you can later save to a file for example.
Development is done in Github: http://github.com/igorgue/py2json
You can report issues or enhancement request here: http://github.com/igorgue/py2json/issues
1 2 3 4 5 | igor@igorlaptop:~$ git clone git://github.com/igorgue/py2json.git igor@igorlaptop:~$ cd py2json/ igor@igorlaptop:~/py2json$ python setup.py install igor@igorlaptop:~/py2json$ python -c 'import py2json' igor@igorlaptop:~/py2json$ |
If you don’t get any error then you’ve successfully installed py2json (sudo might be required in some UNIX environments). Here a example, using py2json to generate a JSON-Schema string:
1 2 3 4 5 6 7 8 9 10 | >>> from py2json import Py2JSON >>> class Foo(object): ... """this class does foo""" ... def bar(self, string='this is a string'): ... print string ... >>> smd = Py2JSON(Foo) >>> smd.schema '{"services": {"bar": {"target": "bar", "parameters": [{"default": "this is a string", "optional": false, "type": "string", "name": "string"}]}}, "envelope": "JSON", "target": null, "transport": "REST", "additionalParameters": true}' >>> |
To exclude a method you can use the exclude parameter:
1 2 3 4 5 6 7 8 9 10 11 | >>> class Foo(object): ... """this class does foo""" ... def bar(self, string='this is a string'): ... print string ... def bar2(self, integer=123): ... print integer ... >>> smd = Py2JSON(Foo, excluded_methods=['bar2']) >>> smd.schema '{"services": {"bar": {"target": "bar", "parameters": [{"default": "this is a string", "optional": false, "type": "string", "name": "string"}]}}, "envelope": "JSON", "target": null, "transport": "REST", "additionalParameters": true}' >>> |
You can use it to store the schema in a string too:
1 2 3 4 5 6 7 | >>> f = open('foo.js', 'w') >>> smd = Py2JSON(Foo) >>> f.write(smd.schema) >>> f.close() >>> print open('foo.js').read() {"services": {"bar": {"target": "bar", "parameters": [{"default": "this is a string", "optional": false, "type": "string", "name": "string"}]}}, "envelope": "JSON", "target": null, "transport": "REST", "additionalParameters": true} >>> |
Py2JSON is a work in progress, suggestions are welcome, patches are awesome :), right now it lacks of a lot of things; since we do not need them right now are not implementing, such as storing attributes.