jsonpickle: Turning Python pickles into JSON

The other day, I saw an interesting question on StackOverflow where the author asked if there was a way to serialize a Python dictionary into a human-readable format. The answer that was given was to use a package called jsonpickle, which will serialize complex Python objects to and from JSON. This article will give you a quick overview of how to use the project.


Getting Started

To get started properly, you will need to download and install jsonpickle. As usual, you can use pip to accomplish this task:

pip install jsonpickle

There are no dependencies for Python 2.6 or greater. For older versions of Python, you will need to install a JSON package, such as simplejson or demjson.


Using jsonpickle

Let's get started by creating a simple class that's based loosely on a Car. Then we will serialize an instance of the class using jsonpickle and deserialize it.

import jsonpickle

########################################################################
class Car(object):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        self.wheels = 4
        self.doors = 5
        
    #----------------------------------------------------------------------
    def drive(self):
        """"""
        print "Driving the speed limit"
    
if __name__ == "__main__":
    my_car = Car()
    serialized = jsonpickle.encode(my_car)
    print serialized
    
    my_car_obj = jsonpickle.decode(serialized)
    print my_car_obj.drive()

If you run this code, you should see something like the following for output:

{"py/object": "__main__.Car", "wheels": 4, "doors": 5}
Driving the speed limit

This worked quite well. The serialized object is very easy to read when it is printed out. Reconstituting the serialized object is also very simple.


Wrapping Up

The jsonpickle package allows the developer to choose what JSON backend they want to use for encoding and decoding the JSON via its load_backend and set_preferred_backend methods. You can also customize the serialization handlers if you want to. Overall, I believe this could be a handy project for developers that need to be able to read their serialized output easily.


Related Reading

Copyright © 2024 Mouse Vs Python | Powered by Pythonlibrary