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.

3 Answers 3

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'
>>>
Sign up to request clarification or add additional context in comments.

3 Comments

Tt works with object_hook. Thanks @Bogdan.
how about model in model
It will not work if the object has datetime.
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

2 Comments

Thanks for your suggestion but for the reason of backward compatibility I need to use JSON.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.