I'm using a D3 script to display pie charts on a Flask-built site, and using JSON to serve the data to those pie charts. However, I'm getting an error message from my D3-powered site when I open it:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
var json_data = "http://the.site/dashboard-data"
@app.route('/dashboard-data')
def display_dashboard_data():
parent_path = '\\'.join(os.path.realpath(__file__).split('\\')[:-1])
file_path = os.path.join(parent_path, 'static\\js\\default_data.json')
with open(file_path, 'r') as file_data:
json_data = json.load(file_data)
return render_template('dashboard_data.html', data=json_data)
<html>
<head>
<meta http-equiv="Content-Type" content="application/json" charset="UTF-8">
</head>
<body>
{'data': [{'id': [...the rest of the JSON is found here.]
</body>
</html>
You should consider creating a separate endpoint that returns JSON response.
@app.route('/artists')
def artists():
parent_path = '\\'.join(os.path.realpath(__file__).split('\\')[:-1])
file_path = os.path.join(parent_path, 'static\\js\\default_data.json')
with open(file_path, 'r') as file_data:
json_data = json.load(file_data)
return jsonify(json_data)
This way, having your client side javascript code make a request to this endpoint to retrieve the data in JSON will be without hassle.