2017-02-17 112 views
0

我在理解jsonify的工作原理時遇到了一些麻煩,即使我閱讀了文檔。正如你可以在下面看到的,我打電話給返回字典的lookup()函數,然後我試圖對它進行jsonify。燒瓶 - 正確使用jsonify

@app.route("/articles") 
def articles(): 

    a = lookup(33496) 
    return jsonify([link=a["link"], title = a["title"]])  #invalid syntax error 

helpers.py

import feedparser 
import urllib.parse 

def lookup(geo): 
    """Looks up articles for geo."""  #this function already parses the 'link' and 'title' form rss feed 

    # check cache for geo 
    if geo in lookup.cache: 
     return lookup.cache[geo] 

    # get feed from Google 
    feed = feedparser.parse("http://news.google.com/news?geo={}&output=rss".format(urllib.parse.quote(geo, safe=""))) 

    # if no items in feed, get feed from Onion 
    if not feed["items"]: 
     feed = feedparser.parse("http://www.theonion.com/feeds/rss") 

    # cache results 
    lookup.cache[geo] = [{"link": item["link"], "title": item["title"]} for item in feed["items"]] 

    # return results 
    return lookup.cache[geo] 

# initialize cache 
lookup.cache = {} 

是我得到的錯誤是無效的語法。任何想法到我做錯了什麼?謝謝

回答

1

我覺得你dict語法是錯誤的。您可以在official documentation中閱讀更多內容。

,我認爲你正在試圖爲如下代碼:

@app.route("/articles") 
def articles(): 
    a = lookup(33496) 
    return jsonify({"link" : a["link"], "title" : a["title"]}) 

具體來說,你應該使用,而不是括號({})和結腸(:)而不是等號大括號。

另一種選擇是讓jsonify()做轉換(如在對方的回答中指出):

@app.route("/articles") 
def articles(): 
    a = lookup(33496) 
    return jsonify(link = a["link"], title = a["title"]) 

不過,我想你會被建議使用創建dict。當您需要創建更大的JSON對象時,它變得更加靈活。

希望這會有所幫助。

+0

然後,如果您需要明確地轉換爲json,那麼jsonify的目的是什麼? – tadm123

+0

是@Jari,問題是我已經使用'jsonify()'指出了它的編輯方式,但是我收到了一些語法錯誤。 – tadm123

+0

我現在嘗試使用你的第一個例子,我也得到了錯誤。嗯 – tadm123