Skip to content Skip to sidebar Skip to footer

Django Convert JSON To CSV

I am working on a function to load data from Data SF and download it as a CSV. I can make a query to their database and accurately display the results in a template, but I cannot w

Solution 1:

Answered by BorrajaX and Mad Wombat in the comments to my original question, the problem was that I was incorrectly referring to the dict keys. The working code:

if request.POST:
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="Search Results.csv"'
    url = request.POST.get('url')
    search_request = requests.get(url, verify=False)
    search_results = search_request.json()
    writer = csv.writer(response)
    writer.writerow(['Tree ID', 'Species', 'DBH', 'Address', 'Latitude', 'Longitude'])
    for obj in search_results:
        writer.writerow([obj['treeid'], obj['qspecies'], obj['dbh'], obj['qaddress'], obj['latitude'], obj['longitude']])
    return response

Post a Comment for "Django Convert JSON To CSV"