Serializing list to JSON Serializing list to JSON django django

Serializing list to JSON


You can use pure Python to do it:

import jsonlist = [1, 2, (3, 4)] # Note that the 3rd element is a tuple (3, 4)json.dumps(list) # '[1, 2, [3, 4]]'


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

try:    import jsonexcept ImportError:    import simplejson as json


Yes, but then what do you do about the django objects? simple json tends to choke on them.

If the objects are individual model objects (not querysets, e.g.), I have occasionally stored the model object type and the pk, like so:

seralized_dict = simplejson.dumps(my_dict,                      default=lambda a: "[%s,%s]" % (str(type(a)), a.pk)                     )

to de-serialize, you can reconstruct the object referenced with model.objects.get(). This doesn't help if you are interested in the object details at the type the dict is stored, but it's effective if all you need to know is which object was involved.