How do I `jsonify` a list in Flask? [duplicate]
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?
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')
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
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)