3

This questions is about generating Source Code, i.e. not something dynamic at runtime but an actual python file that can be manually edited and extended.

Assuming I have a JSON string which deserialises to a non trival group of nested dictionaries, e.g.

{
    'person': { 
        'name': {
            'first_name' : 'foo',
            'last_name' : 'bar'
        }
    }
}

Is there a way to generate python classes, as source code , such that I have a series of classes that nest together and potentially even a constructor at the top level class which can take the same JSON string and populate itself and associated classes?

I've looked at similar questions and some mention warlock, but this seems to generate the code dynamically and also includes type validators and requires a JSON schema rather than an actual example.

I'm looking again for something that will provide class files / source. I started doing this manually but I feel like there might be some pythonic magic out there which will save me time.

http://www.jsonschema2pojo.org/ Is close to what I'm looking for, but the wrong language (It generates Java). I'm looking at taking the output of this service and running https://github.com/natural/java2python over it to create the python I want, but this is getting convoluted and also doesn't include any constructors or class methods that can take the original populated json as an argument.

Does what I'm looking for exist out there?

LaserJesus
  • 8,230
  • 7
  • 47
  • 65
  • The accepted answer on the possible duplicate only provides for dynamic code, as does the supplementary answer to that question. I need a different solution that actually generates source code – LaserJesus Mar 06 '15 at 04:59
  • Ahh right on I see that now. But one of the beauties of a dynamic language like python is that you don't need a "compilation unit" just to get a class you can instantiate. If you'd like to get a plain old python object per json structure, then I suppose you'll need to do some code generation. Sorry for my flag! – Robert Moskal Mar 06 '15 at 05:12
  • No problem on the flag, it generally keeps the place clean. I'm looking for a non-dynamic solution as I want the generated source as a starting point to which I'll add additional attributes and conversion methods. I also want the IDE benefits of strongly defined classes and an SOC between the JSON which could change and my classes which must not. – LaserJesus Mar 06 '15 at 05:17

0 Answers0