我如何在 Flask 中`jsonify` 一个列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12435297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:31:34  来源:igfitidea点击:

How do I `jsonify` a list in Flask?

jsonflask

提问by hllau

Currently Flaskwould raise an error when jsonifying a list.

当前Flask在对列表进行 jsonifying 时会引发错误。

I know there could be security reasons https://github.com/mitsuhiko/flask/issues/170, but I still would like to have a way to return a JSON list like the following:

我知道可能存在安全原因https://github.com/mitsuhiko/flask/issues/170,但我仍然希望有一种方法可以返回如下所示的 JSON 列表:

[
    {'a': 1, 'b': 2},
    {'a': 5, 'b': 10}
]

instead of

代替

{ 'results': [
    {'a': 1, 'b': 2},
    {'a': 5, 'b': 10}
]}

on responding to a application/jsonrequest. How can I return a JSON list in Flask using Jsonify?

在响应application/json请求时。如何使用 Jsonify 在 Flask 中返回 JSON 列表?

采纳答案by FogleBird

jsonifyprevents you from doing this in Flask 0.10 and lower for security reasons.

jsonify出于安全原因,阻止您在 Flask 0.10 及更低版本中执行此操作。

To do it anyway, just use json.dumpsin the Python standard library.

无论如何,只需json.dumps在 Python 标准库中使用即可。

http://docs.python.org/library/json.html#json.dumps

http://docs.python.org/library/json.html#json.dumps

回答by mianos

You can't but you can do it anyway like this. I needed this for jQuery-File-Upload

你不能,但你可以这样做。我需要这个用于 jQuery-File-Upload

import json
# get this object
from flask import Response

#example data:

    js = [ { "name" : filename, "size" : st.st_size , 
        "url" : url_for('show', filename=filename)} ]
#then do this
    return Response(json.dumps(js),  mimetype='application/json')

回答by Geordee Naliyath

This is working for me. Which version of Flask are you using?

这对我有用。您使用的是哪个版本的 Flask?

from flask import jsonify

...

@app.route('/test/json')
def test_json():
    list = [
            {'a': 1, 'b': 2},
            {'a': 5, 'b': 10}
           ]
    return jsonify(results = list)

回答by Jeff Widman

Flask's jsonify()method now serializes top-level arrays as of this commit, available in Flask 0.11 onwards.

Flask 的jsonify()方法现在在此提交时序列化顶级数组,在 Flask 0.11 以后可用。

For convenience, you can either pass in a Python list: jsonify([1,2,3])Or pass in a series of args: jsonify(1,2,3)

为方便起见,您可以传入一个 Python 列表:jsonify([1,2,3])或传入一系列argsjsonify(1,2,3)

Both will be serialized to a JSON top-level array: [1,2,3]

两者都将序列化为 JSON 顶级数组: [1,2,3]

Details here: http://flask.pocoo.org/docs/dev/api/#flask.json.jsonify

详情请见:http: //flask.pocoo.org/docs/dev/api/#flask.json.jsonify

回答by stonefury

Solved, no fuss. You can be lazy and use jsonify, all you need to do is pass in items=[your list].

解决了,不客气。你可以懒惰使用 jsonify,你需要做的就是传入 items=[your list]。

Take a look here for the solution

看看这里的解决方案

https://github.com/mitsuhiko/flask/issues/510

https://github.com/mitsuhiko/flask/issues/510

回答by Hiro

A list in a flask can be easily jsonify using jsonifylike:

使用jsonify可以轻松地对烧瓶中的列表进行jsonify,例如:

from flask import Flask,jsonify
app = Flask(__name__)

tasks = [
    {
        'id':1,
        'task':'this is first task'
    },
    {
        'id':2,
        'task':'this is another task'
    }
]

@app.route('/app-name/api/v0.1/tasks',methods=['GET'])
def get_tasks():
    return jsonify({'tasks':tasks})  #will return the json

if(__name__ == '__main__'):
    app.run(debug = True)

回答by Yor Jaggy

If you are searching literally the way to return a JSON listin flask and you are completly sure that your variable is a list then the easy way is (where binis a list of 1's and 0's):

如果您从字面上搜索在烧瓶中返回JSON 列表的方法,并且您完全确定您的变量是一个列表,那么简单的方法是(其中bin是 1 和 0 的列表):

   return jsonify({'ans':bin}), 201

Finally, in your client you will obtain something like

最后,在您的客户中,您将获得类似

{ "ans": [ 0.0, 0.0, 1.0, 1.0, 0.0 ] }

{ "ans": [ 0.0, 0.0, 1.0, 1.0, 0.0 ] }

回答by Madhan Ganesh

josonify works..but if you intend to just pass an array without the 'results' key, you can use json library from python. The following conversion works for me..

josonify 工作..但是如果你打算只传递一个没有'results'键的数组,你可以使用python中的json库。以下转换对我有用..

 import json

 @app.route('/test/json')
 def test_json():
 list = [
        {'a': 1, 'b': 2},
        {'a': 5, 'b': 10}
       ]
 return json.dumps(list))