[json] How do I `jsonify` a list in Flask?

Currently Flask would raise an error when jsonifying a list.

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:

[
    {'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?

This question is related to json flask

The answer is


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():
 list = [
        {'a': 1, 'b': 2},
        {'a': 5, 'b': 10}
       ]
 return json.dumps(list))

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

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: http://flask.pocoo.org/docs/dev/api/#flask.json.jsonify


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


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


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)

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)