从 Flask 终结点检索 JSON



我正在使用 D3 脚本在 Flask 构建的站点上显示饼图,并使用 JSON 将数据提供给这些饼图。但是,当我打开 D3 驱动的站点时,我收到一条错误消息:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

我的 D3 驱动的 .js 文件包含以下行,该行检索饼图的 JSON:

var json_data = "http://the.site/dashboard-data"

我在 Flask 驱动的"app.py"文件中的 Python 代码如下所示(特别是对于包含我的 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)

JSON 看起来没有问题,但我的假设是上述站点错误是由单引号而不是双引号的存在引起的。此外,问题也可能是 JSON 存储在 HTML 标记中。以下是包含 JSON 的网站的外观:

<html>
<head>
<meta http-equiv="Content-Type" content="application/json" charset="UTF-8">
</head>
<body>
{&#39;data&#39;: [{&#39;id&#39;: [...the rest of the JSON is found here.]
</body>
</html>

所以问题是:将此 JSON 提供给我的 D3 页面的最佳方法是什么?

注意:我使用 Github Gist 开发了 D3 代码,在查看 JSON 文件中的内容时,它有一个非常方便的"原始"选项。该原始端点将具有我的应用程序没有的 .json 扩展名(与此类似)。有没有办法在我自己的应用程序中模拟"原始"端点?

应考虑创建一个返回 JSON 响应的单独终结点。

@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)

这样,让您的客户端 JavaScript 代码向此端点发出请求以检索 JSON 中的数据将没有麻烦。

最新更新