Currently Flask would raise an error when jsonifying a list.

I know there could be security reasons , but I still would like to have a way to return a JSON list like the following:

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

instead of

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

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

2

8 Answers

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') 
5

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.

7

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) 
2

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:

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

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) 
1

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

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) 
1