Answer the question
In order to leave comments, you need to log in
What causes the error when using simplejson .dumps()?
Hello.
An error occurs when trying to encode a QuerySet in JSON and then pass it through Ajax, tell me where I went wrong.
import simplejson
hotel_list = Hotel.objects.filter(id__range=(5, 15)) # Берем из бд срез 15 элементов
hotel_json = simplejson.dumps([hotel_item for hotel_item in hotel_list])
File "/usr/lib64/python2.7/site-packages/simplejson/encoder.py", line 192, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <Hotel: Globus> is not JSON serializable
Answer the question
In order to leave comments, you need to log in
The dumps method converts simple dict, list, unicode/str objects to json, and you are trying to serialize the model.
[hotel_item for hotel_item in hotel_list]
# можно проще
list(hotel_list)
The module simplejson
can serialize/deserialize instances of arbitrary classes. The function dumps
has a parameter for this default
. Example:
import simplejson
class SomeClass(object):
def __init__(self, x, y):
self.x = x
self.y = y
def custom_serrializer(obj):
if isinstance(obj, SomeClass):
return {"x": obj.x, "y": obj.y}
raise TypeError(repr(o) + " is not JSON serializable")
print simplejson.dumps({"key": SomeClass(1,2)}, default=custom_serrializer)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question