[Django]-Map object is not JSON serializable

46๐Ÿ‘

โœ…

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)
๐Ÿ‘คknbk

16๐Ÿ‘

if someone come across this problme when using map(),you can try using list(map()) to solve this problem.

๐Ÿ‘คSong

Leave a comment