Sometimes we have to parse/serialize the python object data in JSON for sending the data to the server.
There are may way to do this, one of such way is to serialize the object inside the __repr__ method.
In this post, I am going to explain to you that how to create a JSON type record in python.Below is the example of a python class which implements the JSON serialization.
import json from collections import OrderedDict def jsonDefault(OrderedDict): return OrderedDict.__dict__ class SampleClass(object): def __init__(self,*args,**kwargs):pass def __repr__(self): return json.dumps(self, default=jsonDefault, indent=4) def add_record_as_data(self,_record): self.__dict__.update(_record.__dict__) def add_record_as_attr(self,_record): self.record = _record obj = SampleClass() obj.name = 'name' print (obj) { "name": "name" }
In the above example we have create a jsonDefault data handler which used inside the __repr__ method of SampleClass class as : json.dumps(self, default=jsonDefault, indent=4)
That’s all for today. I hope this blog will help you. I’d be very grateful if you’d write your opinions, comments, and suggestions to keep the page updated and interesting.
You may also like our post on Python Imaging Library(PIL) Examples.
Be the first to comment.