Python Programming from the Frontlines

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.

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

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.

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: