简体   繁体   中英

Flask jsonify - how to send string back?

I'm building API that sends result back in string format.

@app.route('/', methods=['POST'])
def converter():
    content = request.json
    # translate() - english to hindi
    converted = translate(content)
    print converted
    #prints string normally
    return jsonify({"result":converted})

When try curl -H "Content-Type: application/json" -X POST -d '{"text":"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor."}' http://localhost:5000/ it sends me back

{
  "result": "\u041b\u043e\u0440\u044d\u043c \u0438\u043f\u0441\u04af\u043c \u0434\u043e\u043b\u043e\u0440 \u0441\u0438\u0442 \u0430\u043c\u044d\u0442, c\u043e\u043d\u0441\u044dc\u0442\u044d\u0442\u04af\u044d\u0440 \u0430\u0434\u0438\u043f\u0438\u0441c\u0438\u043d\u0433 \u044d\u043b\u0438\u0442. \u0410\u044d\u043d\u044d\u0430\u043d c\u043e\u043c\u043c\u043e\u0434\u043e \u043b\u0438\u0433\u04af\u043b\u0430 \u044d\u0433\u044d\u0442 \u0434\u043e\u043b\u043e\u0440."
}

How can I send back the strings instead of json object?

Don't wrap the result inside the jsonify call, and simply return converted :

@app.route('/', methods=['POST'])
def converter():
    content = request.json
    converted = translate(content)
    return converted

I think jsonify uses ASCII by default. There is a configuration option:

app.config['JSON_AS_ASCII'] = False

that will set the default to unicode.

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