[英]Flask: Is it possible to return a set as a JSON response
Whilst using Flask can one return a set as a json response from a rest endpoint? 虽然使用Flask可以将一个集合作为来自休息端点的json响应返回?
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. 使用flask的
jsonify
返回JSON响应。 Also, don't use list
as a variable name and convert the unique set
back to list
. 另外,不要将
list
用作变量名,并将唯一set
转换回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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.