Flask: Is it possible to return a collection as a JSON response… here is a solution to the problem.
Flask: Is it possible to return a collection as a JSON response
While using Flask, can I return a set as JSON response from the REST endpoint?
For example:
@app.route('/test')
def test():
list = [1, 1, 1, 1, 2, 2, 2, 2, 3, 4, 4]
unique_list = set(list)
return json.dumps(unique_list)
I’ve tried it but I get the following error:
TypeError: unhashable type: 'list'
I’ve also tried turning the collection back into a list and returning it. But I’m getting the same error as above.
Any ideas?
Solution
jsonify
with flask returns a JSON response. Also, don’t use list as a variable name and convert the unique set
back to list
.
from flask import jsonify
@app.route('/test')
def test():
my_list = [1, 1, 1, 1, 2, 2, 2, 2, 3, 4, 4]
unique_list = list(set(my_list))
return jsonify(results=unique_list)