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
My D3-powered .js file contains this line which retrieves the JSON for the pie charts:
var json_data = "http://the.site/dashboard-data"
My Python code in the Flask-powered "app.py" file looks like this (specifically for the endpoint containing my JSON):
@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)
The JSON appears without a problem, but my assumption is that the aforementioned site-error is caused by the presence of single-quotes instead of double-quotes. Also, the issue could also be that the JSON is stored within HTML tags. Here's what the site containing the JSON looks like:
<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>
So the question is this: what's the best way to serve up this JSON to my D3 page?
Note: I developed the D3 code using a Github Gist, which had a very convenient "Raw" option when viewing the content in my JSON file. That raw endpoint would have a .json extension in it (similar to this) which my application does not have. Is there a way to mimic that "Raw" endpoint in my own application?
You should consider creating a separate endpoint that returns JSON response.
This way, having your client side javascript code make a request to this endpoint to retrieve the data in JSON will be without hassle.