Is there a python json library for converting json to model objects similar to google-gson?

The standard python json module can convert a json string into dict structures.

But I prefer to convert json to object objects with their parent-child relationships.

I use google-gson in android apps but don’t know which python library could do this.

+9
source share
4 answers

You can let the json module build a dict, and then use object_hook to convert the dict to 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' >>> 
+5
source

You can write your own serializer to 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 
+1
source

In 2018, this can be done with cattrs , using static typing with attrs and mypy.

0
source

And in 2019, jsons is a fantastic option. You can not only deserialize a certain class , but also do it without knowing the target class.

0
source

Source: https://habr.com/ru/post/921014/


All Articles