如何在 Flask 中“ jsonify”一个列表?

当前,在 jsonify 列表时,Flask会引发一个错误。

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

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

而不是

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

如何使用 Jsonify 在 Flask 中返回 JSON 列表?

170747 次浏览

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

from flask import jsonify


...


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

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

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

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

You can't but you can do it anyway like this. I needed this for 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')

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.

import json


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

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

Take a look here for the solution

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

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

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)

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

Details here: https://flask.palletsprojects.com/en/2.2.x/api/?highlight=jsonify#flask.json.jsonify**

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

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)

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

   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 ] }