从 Flask 端点检索 JSON
Retriving JSON from Flask endpoint
我正在使用 D3 脚本在 Flask 构建的站点上显示 pie charts,并使用 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"
我的 Python 在 Flask 驱动的 "app.py" 文件中的代码看起来像这样(专门针对包含我的 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>
{'data': [{'id': [...the rest of the JSON is found here.]
</body>
</html>
所以问题是:将此 JSON 提供到我的 D3 页面的最佳方式是什么?
注意:我使用 Github Gist 开发了 D3 代码,当查看我的 JSON 文件中的内容时,它有一个非常方便的 "Raw" 选项。该原始端点将具有我的应用程序没有的 .json 扩展名(类似于 this)。有没有办法在我自己的应用程序中模仿 "Raw" 端点?
您应该考虑创建一个单独的端点,returns 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 中的数据将毫无困难。
我正在使用 D3 脚本在 Flask 构建的站点上显示 pie charts,并使用 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"
我的 Python 在 Flask 驱动的 "app.py" 文件中的代码看起来像这样(专门针对包含我的 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>
{'data': [{'id': [...the rest of the JSON is found here.]
</body>
</html>
所以问题是:将此 JSON 提供到我的 D3 页面的最佳方式是什么?
注意:我使用 Github Gist 开发了 D3 代码,当查看我的 JSON 文件中的内容时,它有一个非常方便的 "Raw" 选项。该原始端点将具有我的应用程序没有的 .json 扩展名(类似于 this)。有没有办法在我自己的应用程序中模仿 "Raw" 端点?
您应该考虑创建一个单独的端点,returns 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 中的数据将毫无困难。