Map object is not serializable JSON

This happens on a return JSONResponsethat was added in Django 1.7. and is a wrapper around json.dumps. However, an error occurs in this case. I am sure that the data is correct and can be serialized in JSON through the Python shell.

What is the correct way to serialize data in 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 of this error:

<map object at 0x7fa3435f3048> is not JSON serializable

print(data) gives:

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

+4
source share
1 answer

map()in Python 3 is a generator function that is not serialized in JSON. You can make it serializable by translating it into 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)
+12
source

Source: https://habr.com/ru/post/1617917/


All Articles