Search code examples
djangodjango-serializer

Serialize data to json formate using native serializer Django


I have this dictionary which I need to pass to another view, knowing that possible ways of doing that are either through sessions or cache, now when I am trying to pass to session it is throwing me an error that data is not JSON serializable probably because I have DateTime fields inside this dictionary

  session_data = serializers.serialize('json',session_data)

error on above statement

'str' object has no attribute '_meta'

updated date is somewhat in this format

{'city_name': 'Srinagar', 'description': 'few clouds', 'temp': 26.74, 'feels_like': 27.07, 'max_temp': 26.74, 'min_temp': 26.74, 'sunrise': datetime.time(6, 11, 10), 'sunset': datetime.time(18, 43, 59)}

Solution

  • Your session_data is already a dictionary. Since Django's serializer focuses on serializing an iterable of model object, that thus will not work.

    You can make use of Django's DjangoJSONEncoder [Django-doc] to serialize Python objects that include date, datetime, time and/or timedelta objects.

    You thus can work with:

    from django.core.serializers.json import DjangoJSONEncoder
    
    encoder = DjangoJSONEncoder()
    session_data = encoder.encode(session_data)

    If you plan to return a JSON blob as a HTTP response, you can simply let the JsonResponse do the encoding work:

    from django.http import JsonResponse
    
    # …
    return JsonResponse(session_data)