Search code examples
pythonjsondjangonested-lists

How do I format a nested python dictionary and write it to a json file?


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!


Solution

  • You don't need to save json to a file.

    You just need to use JsonResponse

    def generateGraph():
        data = {
            "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]
                    }
                }
            }
        }
    
    return JsonResponse(data)