9

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.

michael.luk
  • 551
  • 2
  • 6
  • 11

3 Answers3

8

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'
>>>
Community
  • 1
  • 1
Bogdan
  • 23,890
  • 3
  • 69
  • 61
1

You could write your own serializer to make it work with json, but why not use pyyaml which supports it out of the box:

>>> import yaml
>>> class Foo:
...    def bar(self):
...       print 'Hello I am bar'
...    def zoo(self,i):
...       self.i = i
...       print "Eye is ",i
... 
>>> f = Foo()
>>> f.zoo(2)
Eye is  2
>>> s = yaml.dump(f)
>>> f2 = yaml.load(s)
>>> f2.zoo(3)
Eye is  3
>>> s
'!!python/object:__main__.Foo {i: 2}\n'
>>> f2 = yaml.load(s)
>>> f2.i
2
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
0

In 2018 it can be done with cattrs, utilizing static typing with attrs and mypy

enomad
  • 1,053
  • 9
  • 16