A
A
Anton Manevant2014-02-25 14:40:55
Django
Anton Manevant, 2014-02-25 14:40:55

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])

After that, an error like this occurs:
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

1. Tell me how to correctly encode QuerySet in JSON.
2. Where can I read the FAQ or the simplejson guide.
3. This example of the .dumps method was found on StackOverflow, tell us in more detail what kind of syntax this is.
Thank you very much in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
U
un1t, 2014-02-25
@Manevant

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)

Read more about serialization here.
https://docs.djangoproject.com/en/dev/topics/seria...

S
sheknitrtch, 2014-02-25
@sheknitrtch

The module simplejsoncan serialize/deserialize instances of arbitrary classes. The function dumpshas 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)

Details in the documentation .

M
MagNet, 2014-02-26
@MagNet

one.

from django.core import serializers
data = serializers.serialize("json", Hotel.objects.filter(id__range=(5, 15)))

2. https://docs.djangoproject.com/en/dev/topics/seria...
3. simplejson.readthedocs.org/en/latest/#simplejson.dumps

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question