Map object is not JSON serializable

Peter G. picture Peter G. · Nov 30, 2015 · Viewed 17.3k times · Source

This happens when returning a JSONResponse, which was added in Django 1.7. and is a wrapper around json.dumps. However, in this case it results in an error. I'm sure the data is correct and can be serialized to JSON through Python shell.

What is the right way to serialize the data to JSON?

from django.http import JsonResponse
from collections import OrderedDict

data = OrderedDict([('doc', '546546545'), ('order', '98745'), ('nothing', '0.0')])

return JsonResponse(data) # doesn't work, JSONRenderer().render(data) works

Results in this error:

<map object at 0x7fa3435f3048> is not JSON serializable

print(data) gives:

OrderedDict([('doc', '546546545'), ('order', '98745'), ('nothing', '0.0')])

Answer

knbk picture knbk · Nov 30, 2015

map() in Python 3 is a generator function, which is not serializeable in JSON. You can make it serializeable by converting it to a list:

from django.http import JsonResponse
from collections import OrderedDict

def order(request):    
    bunch = OrderSerializer(Order.objects.all(), many=True)
    headers = bunch.data[0].keys()
    # consume the generator and convert it to a list here
    headers_prepared = list(map(lambda x: {'data': x} , headers))
    ordered_all = (('columns', headers_prepared), ('lines', bunch.data))
    data = OrderedDict(ordered_all)
    return JsonResponse(data)