Reputation: 4818
i have a class (non model)
from django.utils import simplejson
class myclass:
def __init(self):
self.x = "1877"
self.y = "1410"
self.z = "400"
self.w = "67"
self.a ="0"
self.b = "1"
self.c = "319996"
self.d ="187702"
self.t = "168000"
def ajaxRes(request):
mobj = myclass;
json_str = simplejson.dumps(mobj)
return HttpResponse(json_str,mimetype ="application/x-javascript")
i got the follwoing error :
class myapp.views.myclass at 0x7faadc020c18> is not JSON serializable
I also tried the serializers of django but it seems only work for model class
from django.core import serializers
data = serializers.serialize("json", mobj.objects.all())
throws error that mobj
does not have any attribute objects.
How can one serialize a class in django [json format]
.
Upvotes: 1
Views: 2034
Reputation: 4806
You need to prepare simplejson serializer to handle your class:
from django.utils import simplejson
class HandleMyClass(simplejson.JSONEncoder):
""" simplejson.JSONEncoder extension: handle MyClass"""
def default(self, obj):
if isinstance(obj, MyClass):
return obj.__dict__
return simplejson.JSONEncoder.default(self, obj)
data = simplejson.dumps( dictionary, cls=HandleMyClass )
Upvotes: 4