Whilst using Flask can one return a set as a json response from a 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 this and get the following error:
TypeError: unhashable type: 'list'
I've also tried turning the set back into a list and returning that instead. However I am faced with the same error as above.
Any ideas?
Use flask's jsonify
to return 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)