3

I need to use a JSON file created by one of the views in some D3 code in a template. I can load the file with D3 with

d3.json("nameOfTheFile.json", function (error, data) {
  // ...
}

How can I create and serve this file from a Flask view? When I run the same script from IPython notebook I export the file with

dataFrame.to_json(nameOfTheFile.json, orient='records', date_format='iso')

but that instruction does not work from the view.

davidism
  • 121,510
  • 29
  • 395
  • 339

1 Answers1

4

You don't need (or want) to write anything to a file here. You can create the JSON and return it from a flask method:

from flask import Flask, Response

@app.route('/getMyJson')
def getMyJson():
    json = dataFrame.to_json(orient='records', date_format='iso')
    response = Response(response=json, status=200, mimetype="application/json")
    return(response)

The d3 then becomes:

d3.json("/getMyJson", function (error, data) {
  // ...
  // Operations with those data
  // ...
}
Mark
  • 106,305
  • 20
  • 172
  • 230