Serializing list to JSON


Question

I am sending information between client and Django server, and I would like to use JSON to this. I am sending simple information - list of strings. I tried using django.core.serializers, but when I did, I got

AttributeError: 'str' object has no attribute '_meta'

It seems this can be used only for Django objects. How can I serialize simple, Python objects?

1
43
7/6/2012 5:54:43 PM

Accepted Answer

You can use pure Python to do it:

import json
list = [1, 2, (3, 4)] # Note that the 3rd element is a tuple (3, 4)
json.dumps(list) # '[1, 2, [3, 4]]'
83
1/27/2010 2:53:03 PM

If using Python 2.5, you may need to import simplejson:

try:
    import json
except ImportError:
    import simplejson as json

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon