jsonpickle: Turning Python pickles into JSON

Posted by Mike on August 13th, 2014 filed in Cross-Platform, Python

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

Print Friendly

  • Freelance Philosophy

    I don’t think you need jsonpickle for your example, you could just use:

    my_car.__dict__

    I would be curious to see an application which demands using jsonpickle for accessing the methods of a class.

  • http://www.blog.pythonlibrary.org/ Mike Driscoll

    The objective is to be able to serialize objects in Python in a human readable format. The normal Python serialization technique is to use pickle, which is a bit difficult to understand if you open that up in a text editor.

    —————–
    Mike Driscoll

    Blog: http://blog.pythonlibrary.org
    Book: https://gumroad.com/l/bppWr

  • http://arkadefr.github.io/ aRkadeFR

    Excellent for small project without ORM

  • Evans

    My initial thought was what’s the need for this module, then I remembered how difficult it is to read pickled objects in text files.

    Thanks Mike, it now makes sense – and I will give it a try.

  • megan

    I tried to use jsonpickle, but right away I got the “AttributeError: ‘_UnpickleDispatch’ object has no attribute ‘__name__'” error. I did not feel like fighting to make this work, so I gave up. This was the error:

    nixd/opt/python2.7-privatepractice/lib/python2.7/site-packages/jsonpickle/pickler.pyc in _flatten_obj_instance(self, obj)

    349 rv_as_list+=[None]*insufficiency

    350

    –> 351 if rv_as_list[0].__name__ == ‘__newobj__':

    352 rv_as_list[0] = tags.NEWOBJ

    353

    AttributeError: ‘_UnpickleDispatch’ object has no attribute ‘__name__'”