Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving .json file to download

Tags:

python

django

I am trying to serve a .json file through this function. The problem is that every time I make the request the browser displays the content instead of downloading the file.

I think it could be due to the fact that I am using .read() as a parameter for the HttpResponse object constructor. However, if I use only the file object, I get the following exception:

TypeError: cannot serialize '_io.BufferedRandom' object

Code

try:
    invoices = models.Invoice.objects.filter(pk__in=document_ids).order_by(*ordering)
    pcustomers = models.CustomerProxy.objects.all()
    mixed_query = list(invoices) + list(pcustomers)

    file = tempfile.NamedTemporaryFile(suffix='.json')
    file.write(serializers.serialize('json', mixed_query).encode())
    file.seek(0)

    response = HttpResponse(file.read(), content_type='application/json')
    response['Content-Disposition'] = 'attachment; filename=%s' % file.name
    response['Content-Length'] = os.path.getsize(file.name)

except Exception:
    raise

return response
like image 555
Ev. Avatar asked May 18 '16 11:05

Ev.


People also ask

How do I download a JSON file?

Pre-filled JSON can be downloaded after logging into the e-filing portal through: 'My Account -> 'Download Pre-Filled for AY 2022-23' and is imported to the utility for pre-filling the personal and the other opened information. Next Attach the pre-filled file of JSON via the system and Tap on “proceed”.

How do I parse a JSON file?

Example - Parsing JSONUse the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

What is JSON format download?

A JSON file stores the data and object in the JSON format. A JSON ( JavaScript object notation )format is a standard format to store and exchange data.


1 Answers

You don't need to go through the whole file generation process to create a downloadable file, you just need to add the Content-Disposition header normally. Does the code below work?

...
mixed_query = list(invoices) + list(pcustomers)
json_str = serializers.serialize('json', mixed_query))
response = HttpResponse(json_str, content_type='application/json')
response['Content-Disposition'] = 'attachment; filename=export.json'
like image 188
raphv Avatar answered Nov 03 '22 22:11

raphv