Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map object is not JSON serializable

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')])

like image 245
Peter G. Avatar asked Nov 29 '15 23:11

Peter G.


2 Answers

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)
like image 54
knbk Avatar answered Oct 09 '22 03:10

knbk


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

like image 38
Song Avatar answered Oct 09 '22 04:10

Song