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.
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.
Python Supports JSON Natively! Python comes with a built-in package called json for encoding and decoding JSON data.
GSON can use the Object definition to directly create an object of the desired type. While JSONObject needs to be parsed manually.
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.
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'
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With