views:

125

answers:

2

I'm trying to figure out a way to serialize some Django model object to JSON format, something like:

j = Job.objects.get(pk=1)
##############################################
#a way to get the JSON for that j variable???
##############################################

I don't want want:

from django.core import serializers
serializers.serialize('json', Job.objects.get(pk=1),ensure_ascii=False)

Because it returns JSON array, not a single object representation.

Any ideas?

One way I'm thinking of: is to find a way to get a hash(attribute,value) of the object and then use simplejson to get the JSON representation of it, however I don't know how to get that hash.

+3  A: 

The hash you are looking for should be in the object's __dict__ attribute:

>>> import json
>>> j = Job.objects.get(pk=1)
>>> json.dumps(j.__dict__)
tcarobruce
didn't work, also _ _dict_ _ returns other cached stuff.
khelll
In order you use json.dumps() with `j.__dict__` you will need to filter `_FOO_cache` keys. You will also have to make sure that all the values are JSON serializable. DateTimeField's use datetime.datetime and are not directly serializable by dumps().
istruble
+2  A: 

How about just massaging what you get back from serializers.serialize? It is not that hard to trim off the square brackets from the front and back of the result.

job = Job.objects.get(pk=1)
array_result = serializers.serialize('json', [job], ensure_ascii=False)
just_object_result = array_result[1:-1]

Not a fancy answer but it will give you just the object in json notation.

istruble
That worked for me. Thanks
khelll