I am looking to run a calculation in my Django view and then write it to a json file. However I am struggling to get the formatting right.
I need the output json file to look something like this:
{
"dates":
{
"year":
{
"total": 1586266,
"upDown": 9.8,
"data": {
"labels": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
"income": [2000, 4000, 6000, 8000, 10000, 12000, 14000, 16000, 18000, 20000, 22000, 24000],
"expenses": [6000, 12000, 18000, 24000, 30000, 36000, 42000, 48000, 54000, 60000, 66000, 72000]
}
}
}
}
Here is what I have in my view:
def generateGraph():
income = [{'income':['2000','2000','2000','2000','2000','2000','2000','2000','2000','2000','2000','2000']}]
expenses = [{'expenses':['1000','1000','1000','1000','1000','1000','1000','1000','1000','1000','1000','1000']}]
labels = [{'labels':['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']}]
total = 1586266
upDown = 9.8
data = [labels, income, expenses]
year = [total,upDown,data]
dates = [year]
with open(
"static/graph.json") as f:json.dump(dates, f)
return HttpResponse(open("static/graph.json", 'r'), content_type = 'application/json; charset=utf8')
However, the output I currently get in my json file is:
[[1586266, 9.8, [[{"labels": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]}], [{"income": ["2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000"]}], [{"expenses": ["1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000"]}]]]]
Thanks!
3
Answers
You have
labels
,income
, andexpenses
each as alist
with a singledict
in it. You just need thedict
.You have
data
,year
anddates
as lists when they need to be dicts.You just have to get everything in the right form:
Just change lists to dictionary:
You don’t need to save json to a file.
You just need to use JsonResponse