Is there a python json library can convert json to model objects, similar to google-gson?

json, python

Solution

You could let the json module construct a dict and then use an `object_hook` to transform the dict into an object, something like this:

>>> import json
>>>
>>> class Person(object):
...     firstName = ""
...     lastName = ""
...
>>>
>>> def as_person(d):
...     p = Person()
...     p.__dict__.update(d)
...     return p
...
>>>
>>> s = '{ "firstName" : "John", "lastName" : "Smith" }'
>>> o = json.loads(s, object_hook=as_person)
>>>
>>> type(o)
<class '__main__.Person'>
>>>
>>> o.firstName
u'John'
>>>
>>> o.lastName
u'Smith'
>>>

Problem

The standard python json module only can convert json string to dict structures. But I prefer to convert json to a model object strutures with their "parent-child" relationship. I use google-gson in Android apps but don't know which python library could do this.

Original source

Related problems