Search code examples
pythondjangoexceptionsimplejson

Why am I getting this simplejson exception?


Why does Django give me this exception

[(7, u'Acura'), (18, u'Alfa Romeo'), ...] is not JSON serializable

When I try

data = VehicleMake.objects.filter(model__start_year__gte=request.GET.get('year',0)).values_list('id','name')
return HttpResponse(simplejson.dumps(data, ensure_ascii=False), mimetype='application/json')

?

It's just a simple list of tuples. It works with my other hard-coded list that's in almost exactly the same format. Is it because the strings are unicode? How do I handle that?


It works fine when I encode it as a dict:

def get_makes(request):
    year = request.GET.get('year',0)
    data = VehicleMake.objects.filter(model__start_year__lte=year, model__stop_year__gte=year).order_by('name').distinct().values_list('id','name')
    return HttpResponse(simplejson.dumps(odict(data), ensure_ascii=False), mimetype='application/json')

Some makes have accented characters... could that be it? Yes, the list is big (~900 makes total).


Solution

  • Instead of

    return HttpResponse(simplejson.dumps(data, ensure_ascii=False), mimetype='application/json')
    

    Use list(data) and modify your Javascript to work with it.

    for(i in values) {
        $select.append('<option value="'+values[i][0]+'">'+values[i][1]+'</option>');
    }