简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM