Python JSON to Object
Arunvel Sriram
1 min read
In Python, json.load()
and json.loads()
takes in object_hook
parameter that helps to convert JSON data in to an object.
The deserialised JSON (dict) is passed as an argument to constructor of the hooked class where we can have the implementation for populating the class attributes.
Example:
class MyData:
def init(self, data):
self.name = data.get("Name")
self.phone = data.get("PhoneNumber")
# main
json.loads('{"Name": "test", "PhoneNumber": "123"}',
object_hook=MyData)
With this discussion, my colleagues shared few more tricks with object_hook
:
https://github.com/python/cpython/issues/96145#issuecomment-1599508607
https://pypi.org/project/dataclasses-json/
0
Subscribe to my newsletter
Read articles from Arunvel Sriram directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Arunvel Sriram
Arunvel Sriram
Software Engineer | Polyglot | DevOps | Open Source