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?
To jsonify a list of objects with Python Flask, we add a method in our object's class to return the object's contents as a dictionary. to create the Gene class that has the serialize method that returns the instance properties in a dictionary.
No, returning a dict in Flask will not apply jsonify automatically. In fact, Flask route cannot return dictionary.
jsonify() is a helper method provided by Flask to properly return JSON data. jsonify() returns a Response object with the application/json mimetype set, whereas json. dumps() simply returns a string of JSON data.
Use json. dumps() to convert a list to a JSON array in Python. The dumps() function takes a list as an argument and returns a JSON String.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With