Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a JSON schema to a python class

Is there a python library for converting a JSON schema to a python class definition, similar to jsonschema2pojo -- https://github.com/joelittlejohn/jsonschema2pojo -- for Java?

like image 701
JD White Avatar asked Sep 17 '12 19:09

JD White


People also ask

Can you convert JSON to Python?

Parse JSON - Convert from JSON to Python If you have a JSON string, you can parse it by using the json.loads() method. The result will be a Python dictionary.

What converts .JSON file into a Python object?

Use jsonpickle module to convert JSON data into a custom Python Object. jsonpickle is a Python library designed to work with complex Python Objects. You can use jsonpickle for serialization and deserialization complex Python and JSON Data. You can refer to Jsonpickle Documentation for more detail.


1 Answers

So far the closest thing I've been able to find is warlock, which advertises this workflow:

Build your schema

>>> schema = {     'name': 'Country',     'properties': {         'name': {'type': 'string'},         'abbreviation': {'type': 'string'},     },     'additionalProperties': False, } 

Create a model

>>> import warlock >>> Country = warlock.model_factory(schema) 

Create an object using your model

>>> sweden = Country(name='Sweden', abbreviation='SE') 

However, it's not quite that easy. The objects that Warlock produces lack much in the way of introspectible goodies. And if it supports nested dicts at initialization, I was unable to figure out how to make them work.

To give a little background, the problem that I was working on was how to take Chrome's JSONSchema API and produce a tree of request generators and response handlers. Warlock doesn't seem too far off the mark, the only downside is that meta-classes in Python can't really be turned into 'code'.

Other useful modules to look for:

  • jsonschema - (which Warlock is built on top of)
  • valideer - similar to jsonschema but with a worse name.
  • bunch - An interesting structure builder thats half-way between a dotdict and construct

If you end up finding a good one-stop solution for this please follow up your question - I'd love to find one. I poured through github, pypi, googlecode, sourceforge, etc.. And just couldn't find anything really sexy.

For lack of any pre-made solutions, I'll probably cobble together something with Warlock myself. So if I beat you to it, I'll update my answer. :p

like image 91
synthesizerpatel Avatar answered Sep 22 '22 13:09

synthesizerpatel