繁体   English   中英

Flask-正确使用jsonify

[英]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.

了解python中的关键字参数。

我认为您的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.

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