109

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
  • 9,879
  • 7
  • 30
  • 35
  • 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

8 Answers8

92

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,440
  • 26
  • 86
  • 126
mianos
  • 943
  • 13
  • 14
  • 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
  • 6
    +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
  • 2,197
  • 3
  • 26
  • 35
FogleBird
  • 74,300
  • 25
  • 125
  • 131
24

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,528
  • 14
  • 12
Geordee Naliyath
  • 1,799
  • 17
  • 28
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: https://flask.palletsprojects.com/en/2.2.x/api/?highlight=jsonify#flask.json.jsonify**

Jeff Widman
  • 22,014
  • 12
  • 72
  • 88
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,992
  • 1
  • 15
  • 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
  • 20,759
  • 10
  • 81
  • 84
Madhan Ganesh
  • 2,273
  • 2
  • 24
  • 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
0

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
  • 405
  • 4
  • 11