Retriving JSON从瓶端点
问题描述:
我使用的是D3的脚本,以显示在烧瓶建网站pie charts,并使用JSON服务于数据的饼图。不过,我从我的D3供电现场收到错误信息,当我打开它:Retriving JSON从瓶端点
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"
在瓶供电“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似乎没有问题,但我的假设是, aforem所提到的网站错误是由单引号而不是双引号引起的。另外,这个问题也可能是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的要点,查看我的JSON文件中的内容时,它有一个非常方便的“原始”选项D3代码。这原将端点有它以.json扩展(类似于this)的我的应用程序没有。有没有办法在我自己的应用程序中模仿“Raw”端点?
答
你应该考虑建立一个单独的终结点返回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中的数据将毫无麻烦。