I am trying to send the JSON Format with added headers in .csv format to a front end for download. While sending a HTTP Response I am facing an "is not JSON serializable" error.
My views.py
file:
from datetime import datetime
from django.shortcuts import render
from django.http import HttpResponse
import json as simplejson
import random
import csv
def DownloadEventLog(request):
downloadeventlog = "[{\"severity\":\"0\",\"description\":\"USB Connected\",\"date\":\"01/01/2015\",\"time\":\"11:35:20\"},{\"severity\":\"3\",\"description\":\"USB Disconnected\",\"date\":\"01/01/2015\",\"time\":\"10:30:19\"}]";
data = simplejson.loads(downloadeventlog)
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="eventlog.csv"'
writer = csv.writer(response)
writer.writerow(data[0].keys())
for row in data:
writer.writerow(row.values())
print response
return HttpResponse(simplejson.dumps(response), content_type = "application/json")
Print response cmd is printing:
Content-Type: text/csv
Content-Disposition: attachment; filename="eventlog.csv"
date,time,severity,description
01/01/2015,11:35:20,0,"USB Connected"
02/02/2015,10:30:19,3,"USB Disconnected"
However the last line is throwing an error as follows:
TypeError at /eventlog/downloadeventlog
<django.http.response.HttpResponse object at 0x9c059ec>is not JSON serializable
Request Method: POST
Request URL: http://127.0.0.1:8001/eventlog/downloadeventlog
Django Version: 1.7.1
Python Version: 2.7.3