Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

json

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.

like image 937
michael.luk Avatar asked Jul 21 '12 07:07

michael.luk


People also ask

What converts .JSON file into a Python object?

Use jsonpickle module to convert JSON data into a custom Python Object. jsonpickle is a Python library designed to work with complex Python Objects. You can use jsonpickle for serialization and deserialization complex Python and JSON Data. You can refer to Jsonpickle Documentation for more detail.

Does Python have JSON library?

Python Supports JSON Natively! Python comes with a built-in package called json for encoding and decoding JSON data.

Is GSON better than JSON?

GSON can use the Object definition to directly create an object of the desired type. While JSONObject needs to be parsed manually.

What is difference between JSON and GSON?

The JSON format was originally specified by Douglas Crockford. On the other hand, GSON is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.


1 Answers

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'
>>>
like image 104
Bogdan Avatar answered Sep 25 '22 02:09

Bogdan