102

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?

hllau
  • 8,871
  • 6
  • 28
  • 34
  • This is no longer a security issue, but it is still considered a best practice to always return a dict : https://softwareengineering.stackexchange.com/a/304638/369319 – Noan Cloarec Jul 01 '20 at 07:11
  • This is not a duplicate because the other question does not deal with lists – G M Mar 08 '22 at 13:31

8 Answers8

88

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')
Roman Kagan
  • 10,292
  • 24
  • 84
  • 124
mianos
  • 912
  • 12
  • 12
  • 1
    There is also flask.json.dumps don't know if this is better than json.dumps – Cameron White Dec 24 '13 at 15:25
  • 3
    @CameronWhite - `flask.json` is shorthand for `try: import simplejson as json; except ImportError: import json` – Ewan Feb 03 '14 at 08:52
  • 5
    +1 for mimetype='application/json', saved me looking for the relevant header :) – Shmil The Cat Apr 03 '14 at 10:16
  • The funny thing is i was stuck on this in the exact same situation (jQuery File Upload) and your code helped me in another way as well. – deweydb Jun 13 '15 at 22:34
  • I like this answer best. From my experience, `Response()` exposes mimetype in a simpler fashion than `make_response()` and just doing `return json.dumps()` doesn't set any headers. – sofly Mar 10 '16 at 22:18
64

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

simanacci
  • 1,879
  • 3
  • 27
  • 32
FogleBird
  • 70,488
  • 25
  • 121
  • 130
21

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)
Andrey
  • 1,428
  • 13
  • 12
Geordee Naliyath
  • 1,731
  • 15
  • 27
12

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

Jeff Widman
  • 19,508
  • 10
  • 68
  • 84
7

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

stonefury
  • 466
  • 4
  • 7
5

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)
Hiro
  • 2,774
  • 1
  • 14
  • 9
1

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)
G M
  • 17,694
  • 10
  • 75
  • 78
Madhan Ganesh
  • 2,211
  • 2
  • 23
  • 19
  • I think this should be the accepted answer, is the only that returns the correct data structure. Thansk a lot – G M Mar 08 '22 at 13:40
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 ] }

Yor Jaggy
  • 315
  • 3
  • 8