我希望在Django视图中运行一个计算,然后将其写入一个json文件,但是我很难得到正确的格式。
我需要输出json文件看起来像这样:
{
"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]
}
}
}
}
以下是我的看法:
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')
但是,我目前在json文件中得到的输出是:
[[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"]}]]]]
谢谢!
3条答案
按热度按时间vaqhlq811#
您不需要将json保存到文件中。
您只需要使用JsonResponse
bkkx9g8r2#
labels
、income
和expenses
都是list
,其中只有一个dict
,您只需要dict
。当需要将
data
、year
和dates
作为dict时,可以将它们作为列表。你只需要把所有的东西都摆在正确的位置:
0ejtzxu13#
只需将列表更改为字典: