Python Tutorial

Friday, September 7, 2012

Python jsonpickle: object serialization and deserialization



jsonpickle is a Python library for serialization and deserialization of complex Python objects to and from JSON.Its support complex python object.
You need install jsonpickle first (pip command pip install jsonpickle)
Lets see a example:


 
import jsonpickle


class Subclass(object):
    subclass_value=10
    def my_fun(self):
        print "this is myfun from Subclass"

class MainClass(object):
    mainclass_data='This is main class data'
    mainclass_value=5
    sc=Subclass()


obj=MainClass()
pickle=jsonpickle.encode(obj,max_depth=1) #Here I set max_depth, so it will not recurse 
unpickleObject=jsonpickle.decode(pickle)  #deeper than 'max_depth' steps into the object 


unpickleObject.sc.my_fun()
print unpickleObject.mainclass_data



max_depth is very important, it's define maximum depth level of recursion. If you have no idea about depth level of recursion just set a mixmum value (max_depth=50000).

Output:
this is myfun from Subclass
This is main class data

0 comments:

Post a Comment