python - is not JSON serializable -
i have 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 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)...'] not json serializable
any ideas ?
i'll add more detailed answer.
it's worth noting queryset.values_list()
method doesn't return list, object of type django.db.models.query.valueslistqueryset
, in order maintain django's goal of lazy evaluation, i.e. db query required generate 'list' isn't performed until object evaluated.
somewhat irritatingly, though, object has custom __repr__
method makes list when printed out, it's not obvious object isn't list.
the exception in question caused fact custom objects cannot serialized in json, you'll have convert list first, with...
my_list = list(self.get_queryset().values_list('code', flat=true))
...then can convert json with...
json_data = json.dumps(my_list)
you'll have place resulting json data in httpresponse
object, which, apparently, should have content-type
of application/json
, with...
response = httpresponse(json_data, content_type='application/json')
...which can return function.
Comments
Post a Comment