【发布时间】:2017-11-12 13:59:20
【问题描述】:
我需要删除前缀“u”,因为我将这些 json 序列化列表传递到前端并使用 javascript 处理它们。 Javascript 无法理解这些“u”。
代码如下:
context['list_of_dicts'] = serialize('json', my_list_of_dicts)
# this function is wrapped with a @json response decorator
@json_response 看起来像:
def json_response(func):
"""
A decorator thats takes a view response and turns it
into json. If a callback is added through GET or POST
the response is JSONP.
"""
def decorator(request, *args, **kwargs):
objects = func(request, *args, **kwargs)
if isinstance(objects, HttpResponse):
return objects
try:
data = simplejson.dumps(objects)
if 'callback' in request.REQUEST:
# a jsonp response!
data = '%s(%s);' % (request.REQUEST['callback'], data)
return HttpResponse(data, "text/javascript")
except:
data = simplejson.dumps(str(objects))
return HttpResponse(data, "application/json")
return decorator
在前端,我收到错误:
Uncaught SyntaxError: Unexpected token u in JSON at position 0
那是因为“u”前缀没有被删除。如何删除“u”前缀,以便我的前端可以解码 JSON?
【问题讨论】:
-
什么是
serialize,如果你想要JSON,为什么不使用json? -
@jonrsharpe:我认为是 Django 方法。
-
我已编辑问题以包含更多代码
-
请提供格式正确的minimal reproducible example。如果您有一个将响应转换为 JSON 的装饰器,您为什么还要自己序列化它?
标签: javascript python json django unicode