JSON serialization with Python

First part of the problem: How should objects serialize to JSON, and can this be exchanged between different languages (.NET/Python) without writing custom Encode/Decoding implementations?

Second part: Why does Python’s Pickle serialize (reflect) an object, but simplejson which mimics the exact same interface behave differently?

Lets work backwards (second part first)

1) Serialize a Python object to JSON, given this code:

import simplejson
import pickle
import jsonpickle

class Person(object):
def __init__(self, name=”):
self.name = name
def __string__(self):
return self.name

p = Person(‘Steve Smith’)
print “Person Object Name: “, p.name

print “Pickle: “, pickle.dumps(p)
print “SimpleJson: “, simplejson.dumps([p.__dict__])
print “JsonPickle: “, jsonpickle.dumps(p)

A simple Person object. The first print statement (Pickle) returns this:

ccopy_reg
_reconstructor
p0
(c__main__
Person
p1
c__builtin__
object
p2
Ntp3
Rp4
(dp5
S’name’
p6
S’Steve Smith’
p7
sb.

Fine…but not very helpful when it comes to JSON. Using simplejson requires you to specify each internally stored datatype. This hardly seems reasonable, why doesn’t simplejson simple do the lifting for you?

Next I found a website where another gentleman shared the same thought/idea. He wrote jsonpickle which utilizes simplejson, but implements the methods the way you would expect them to work. Here is the output of jsonpickle:

{“__classname__”: “Person”, “name”: “Steve Smith”, “__classmodule__”: “__main__”}

This gets us back to the initial question. How should objects serialize to JSON, and can this be exchanged between different languages (.NET/Python) without writing custom Encode/Decoding implementations?

The answer is no. The JSON standard is loosely defined such that it is up to the JSON library author to define how an object is persisted to the JSON specification. More to come…Headley will have to write his .NET class and see how the JSON library on his end implemented it.

Advertisements

One response to “JSON serialization with Python

  1. I do not even know how I ended up here, but I thought
    this post was great. I don’t know who you are but definitely you are going to a famous blogger if you aren’t already šŸ˜‰ Cheers!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s