如何从(json序列化的)词典列表中删除"u"前缀?

Mik*_* Jr -3 javascript python django unicode json

我需要删除"u"前缀,因为我将这些json序列化列表传递到前端并使用javascript处理它们.Javascript无法理解这些"你".

这是代码:

context['list_of_dicts'] = serialize('json', my_list_of_dicts)
# this function is wrapped with a @json response decorator
Run Code Online (Sandbox Code Playgroud)

@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
Run Code Online (Sandbox Code Playgroud)

在前端,我收到错误:

Uncaught SyntaxError: Unexpected token u in JSON at position 0
Run Code Online (Sandbox Code Playgroud)

那是因为"u"前缀尚未删除.如何删除"u"前缀,以便我的前端可以解码JSON?

Mar*_*ers 6

您将数据序列化三次.首先:

context['list_of_dicts'] = serialize('json', my_list_of_dicts)
Run Code Online (Sandbox Code Playgroud)

然后两次以上:

data = simplejson.dumps(str(objects))
Run Code Online (Sandbox Code Playgroud)

str()将对objects您的视图函数返回的表示进行编码,然后将其转换为JSON字符串文档.该str()转换添加u前缀; 您正在序列化Unicode字符串对象文字:

>>> context = {}
>>> context['list_of_dicts'] = u'<Some JSON literal here, correctly encoded>'
>>> import json
>>> json.dumps(str(context))
'"{\'list_of_dicts\': u\'<Some JSON literal here, correctly encoded>\'}"'
Run Code Online (Sandbox Code Playgroud)

你的装饰师有几个问题:

  • 你正在使用一个毯子except处理程序,所以你屏蔽了第一次尝试序列化时出现的任何错误simplejson.dumps().切勿使用毯子except并使异常沉默.你现在不知道那里出了什么问题.另请参阅为什么"除了:传递"一个糟糕的编程习惯?

  • 你似乎是将对象序列化为字典; 如果你要发送回一个JSON对象,构建东西只由Python中的对象第一,然后连载整.

  • 如果你需要自定义序列化逻辑(比如使用Django序列化框架),不要使用@json_response装饰器重新编码,或者至少返回一个HttpResponse实例以避免再次序列化.

  • 三次; 他们不只是"转储(对象)",他们也称它为"str"! (2认同)