is not JSON serializable


Question

I have the following ListView

import json
class CountryListView(ListView):
     model = Country

    def render_to_response(self, context, **response_kwargs):

         return json.dumps(self.get_queryset().values_list('code', flat=True))

But I get following error:

[u'ae', u'ag', u'ai', u'al', u'am', 
u'ao', u'ar', u'at', u'au', u'aw', 
u'az', u'ba', u'bb', u'bd', u'be', u'bg', 
u'bh', u'bl', u'bm', u'bn', '...(remaining elements truncated)...'] 
is not JSON serializable

Any ideas ?

1
47
5/2/2013 10:55:52 AM

Accepted Answer

I'll add a slightly more detailed answer.

It's worth noting that the QuerySet.values_list() method doesn't actually return a list, but an object of type django.db.models.query.ValuesListQuerySet, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.

Somewhat irritatingly, though, this object has a custom __repr__ method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.

The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...

my_list = list(self.get_queryset().values_list('code', flat=True))

...then you can convert it to JSON with...

json_data = json.dumps(my_list)

You'll also have to place the resulting JSON data in an HttpResponse object, which, apparently, should have a Content-Type of application/json, with...

response = HttpResponse(json_data, content_type='application/json')

...which you can then return from your function.

68
5/23/2017 11:47:17 AM

class CountryListView(ListView):
     model = Country

    def render_to_response(self, context, **response_kwargs):

         return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json") 

fixed the problem

also mimetype is important.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon