Serialize datetime to JSON

Issue

How do I get DateTimeField from the Mysql database in Django in JSON format? I got an error when I executed the code Date.time cannot be serialized in json (data holds a lot of values):

data = json.dumps(data)

But this was fixed by adding

ALL_data = serializers.serialize("json", data, ensure_ascii=False)

But now I get 'str' object has no attribute '_meta'.

Solution

DjangoJSONEncoder solved my problem.

import json
from django.core.serializers.json import DjangoJSONEncoder
data = json.dumps(data, cls=DjangoJSONEncoder)

Answered By – Rakesh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published