Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is not JSON serializable

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 ?

like image 915
tuna Avatar asked May 02 '13 10:05

tuna


People also ask

Is not JSON serializable error?

The Python "TypeError: Object of type function is not JSON serializable" occurs when we try to serialize a function to JSON. To solve the error, make sure to call the function and serialize the object that the function returns.

Is not JSON serializable error in Python?

The Python "TypeError: Object of type method is not JSON serializable" occurs when we try to serialize a method to JSON. To solve the error, make sure to call the method and serialize the object that the method returns.

Why is a set not JSON serializable?

The Python "TypeError: Object of type set is not JSON serializable" occurs when we try to convert a set object to a JSON string. To solve the error, convert the set to a list before serializing it to JSON, e.g. json. dumps(list(my_set)) . Here is an example of how the error occurs.

What types are JSON serializable?

The following types are serialized to JSON arrays: AZStd::array. AZStd::fixed_vector. AZStd::forward_list.


1 Answers

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.

like image 62
Aya Avatar answered Sep 20 '22 18:09

Aya