[英]Flask - Using jsonify properly
盡管閱讀了文檔,但在理解jsonify
工作方式時遇到了一些麻煩。 如您在下面看到的,我正在調用lookup()
函數,該函數返回一個字典,然后嘗試對其進行json化。
@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 = {}
我收到的錯誤是語法無效。 知道我做錯了什么嗎? 謝謝
您不需要方括號,擺脫它們。
return jsonify(link=a["link"], title=a["title"])
# ^At this point ^ and this one.
我認為您的dict
語法錯誤。 您可以在官方文檔中了解更多信息 。
我認為您正在嘗試的代碼如下:
@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"])
不過,我建議您最好使用create dict
。 當您需要創建更大的JSON對象時,它變得更加靈活。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.