How do I `jsonify` a list in Flask?

JsonFlask

Json Problem Overview


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?

Json Solutions


Solution 1 - Json

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

Solution 2 - Json

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

Solution 3 - Json

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)

Solution 4 - 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

Solution 5 - Json

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

Solution 6 - Json

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)

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

Solution 8 - Json

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhllauView Question on Stackoverflow
Solution 1 - JsonmianosView Answer on Stackoverflow
Solution 2 - JsonFogleBirdView Answer on Stackoverflow
Solution 3 - JsonGeordee NaliyathView Answer on Stackoverflow
Solution 4 - JsonJeff WidmanView Answer on Stackoverflow
Solution 5 - JsonstonefuryView Answer on Stackoverflow
Solution 6 - JsonHiroView Answer on Stackoverflow
Solution 7 - JsonMadhan GaneshView Answer on Stackoverflow
Solution 8 - JsonYor JaggyView Answer on Stackoverflow