Map object is not JSON serializable

20,017

Solution 1

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)

Solution 2

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

Share:
20,017
Peter G.
Author by

Peter G.

My profile is that of a software product owner with a strong engineering background. I like building end-to-end solutions that typically require a mix of technical skills, business skills, and mathematical knowledge. I understand how to optimize data algorithms, and how to explain my findings. My technical background allows me to deal with data at scale. I'm an active learner with a strong aptitude towards technology and discovering the new. My areas of expertise are Mobile and Data Analytics. I have a niche for data-driven apps. That area poses a set of new challenges and opportunities and also it is one of the most rapidly growing fields.

Updated on September 08, 2020

Comments

  • Peter G.
    Peter G. over 3 years

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