Sanic: response.json() escapes slashes? "/" -> "\/"

Created on 15 Nov 2017  ·  2Comments  ·  Source: sanic-org/sanic

env: ubuntu 16.04, pyvenv-3.5, sanic-0.6.0

import json as json_origin
from sanic import Sanic
from sanic.response import HTTPResponse, text, json

app = Sanic(__name__)

async def get_item_handler_a(request, item_id):
    url = app.url_for('get_item_handler_a', item_id=item_id)
    d = { 'id': item_id, 'url': url }
    return json(d)

async def get_item_handler_b(request, item_id):
    url = app.url_for('get_item_handler_b', item_id=item_id)
    d = { 'id': item_id, 'url': url }
    return text(json_origin.dumps(d))

async def get_item_handler_c(request, item_id):
    url = app.url_for('get_item_handler_c', item_id=item_id)
    d = { 'id': item_id, 'url': url }
    return HTTPResponse(json_origin.dumps(d), status=200, headers=None, content_type='application/json')

app.add_route(get_item_handler_a, '/items_a/<item_id:int>', methods=['GET'])
app.add_route(get_item_handler_b, '/items_b/<item_id:int>', methods=['GET'])
app.add_route(get_item_handler_c, '/items_c/<item_id:int>', methods=['GET'])

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8080, debug=True)

result:

# "/" are escaped
$ curl http://localhost:8080/items_a/666/
{"id":666,"url":"\/items_a\/666"}

# OK with json.dump
$ curl http://localhost:8080/items_b/666/
{"id": 666, "url": "/items_b/666"}

# walk around by constructing HTTPResponse
curl http://localhost:8080/items_c/666/
{"id": 666, "url": "/items_c/666"}

so, with response.json(), the strings content are escaped.

Most helpful comment

solved, it's due to ujson

return json(result, ensure_ascii=False, escape_forward_slashes=False)

All 2 comments

solved, it's due to ujson

return json(result, ensure_ascii=False, escape_forward_slashes=False)

Is it any reason why sanic use this library instead of the regular one or others?
I find myself not using response.json because of that
The most clear reason is because it converts dates to timestamps which I don't like and need at all...

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fiecato picture fiecato  ·  3Comments

olalonde picture olalonde  ·  3Comments

eseglem picture eseglem  ·  4Comments

davidtgq picture davidtgq  ·  3Comments

misakar picture misakar  ·  4Comments