2017-08-27 60 views
0

我使用的是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> 
     {&#39;data&#39;: [{&#39;id&#39;: [...the rest of the JSON is found here.] 
    </body> 
</html> 

所以現在的問題是:什麼是擔任了這個JSON我D3網頁的最佳方式?

注:我公司開發使用Github的要點,查看我的JSON文件中的內容時,它有一個非常方便的「原始」選項D3代碼。這原將端點有它以.json擴展(類似於this)的我的應用程序沒有。有沒有辦法在我自己的應用程序中模仿「Raw」端點?

回答

3

你應該考慮建立一個單獨的終結點返回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中的數據將毫無麻煩。