简体   繁体   English

从Flask端点检索JSON

[英]Retriving JSON from Flask endpoint

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. 我正在使用D3脚本在Flask构建的站点上显示饼图 ,并使用JSON将数据提供给那些饼图。 However, I'm getting an error message from my D3-powered site when I open it: 但是,当我打开D3网站时,我收到一条错误消息:

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: 我的D3驱动的.js文件包含以下行,该行检索饼图的JSON:

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

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. JSON似乎没有问题,但是我认为上述站点错误是由单引号而不是双引号引起的。 Also, the issue could also be that the JSON is stored within HTML tags. 另外,问题还可能是JSON存储在HTML标记内。 Here's what the site containing the JSON looks like: 包含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>

So the question is this: what's the best way to serve up this JSON to my D3 page? 所以问题是这样的:向我的D3页面提供JSON的最佳方法是什么?

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. 注意:我使用Github Gist开发了D3代码,该代码在查看JSON文件中的内容时具有非常方便的“原始”选项。 That raw endpoint would have a .json extension in it (similar to this ) which my application does not have. 该原始端点中将带有.json扩展名(类似于this ),而我的应用程序则没有。 Is there a way to mimic that "Raw" endpoint in my own application? 有没有办法模仿我自己的应用程序中的“原始”端点?

You should consider creating a separate endpoint that returns JSON response. 您应该考虑创建一个单独的端点,该端点返回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)

This way, having your client side javascript code make a request to this endpoint to retrieve the data in JSON will be without hassle. 这样,让您的客户端javascript代码向此终结点发出请求以JSON形式检索数据将毫无麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM