Wednesday, July 14, 2010

python: using simplejson to JSON serialize

When you search the web for how to json serialize you data you first encounter a module called simplejson. But using simplejson is the problem...no one exactly says how you can use it...

The simplejson library is fortunately friendly with python dictionaries. And hence here is a small example to start off with:
import simplejson

vals={}
vals['user'] = 'deostroll'
vals['visits'] = 46
vals['date_of_birth'] = '10/27/1986'

print simplejson.dumps(vals)
This library sadly doesn't know how to serialize a class object. However the work around to that is quite simple too.
class a():
    pass
    
x = a()

x.name = 'Arun'
x.designation = 'Software Engineer'
x.department = 'Media & Entertainment'
x.age = 24

print simplejson.dumps(x.__dict__)
Hope you've understood how you can now use simplejson library. Happy programming

No comments: