简体   繁体   English

Flask-正确使用jsonify

[英]Flask - Using jsonify properly

I'm having some trouble in understanding how jsonify works even though I went through the documentation. 尽管阅读了文档,但在理解jsonify工作方式时遇到了一些麻烦。 As you can see below, I'm calling the lookup() function which returns a dictionary, then I'm trying to jsonify it. 如您在下面看到的,我正在调用lookup()函数,该函数返回一个字典,然后尝试对其进行json化。

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

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

my helpers.py : 我的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 = {}

The error that I'm getting is of invalid syntax. 我收到的错误是语法无效。 Any idea into what I'm doing wrong? 知道我做错了什么吗? Thanks 谢谢

You dont need the square brackets, get rid of them. 您不需要方括号,摆脱它们。

return jsonify(link=a["link"], title=a["title"])
             # ^At this point                 ^ and this one.

Read about keyword arguments in python. 了解python中的关键字参数。

I think your dict syntax is wrong. 我认为您的dict语法错误。 You can read about more in official documentation . 您可以在官方文档中了解更多信息

The code that I think you are trying for is as follows: 我认为您正在尝试的代码如下:

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

Specifically you should use curly braces instead of brackets ( {} ) and colon ( : ) instead of equals sign. 具体来说,你应该使用,而不是括号大括号( {}和冒号( : )而不是等号。

Another option is to let jsonify() to do the conversion (as pointed out in the other answer): 另一个选择是让jsonify()进行转换(如另一个答案所指出):

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

Nevertheless, I think you would be well advised to use create a dict . 不过,我建议您最好使用create dict It becomes more flexible when you need to create larger JSON objects. 当您需要创建更大的JSON对象时,它变得更加灵活。

Hope this helps. 希望这可以帮助。

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

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