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

时间:2017-06-10 18:19:13

标签: javascript python json django unicode

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

以下是代码:

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?

1 个答案:

答案 0 :(得分:6)

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

context['list_of_dicts'] = serialize('json', my_list_of_dicts)

然后两次以上:

data = simplejson.dumps(str(objects))

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

u

你的装饰师有几个问题:

  • 您正在使用毯子>>> 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>\'}"' 处理程序,因此您正在屏蔽首次尝试使用except进行序列化时出现的错误。切勿使用毯子simplejson.dumps()并使例外无声。你现在不知道那里出了什么问题。另请参阅Why is "except: pass" a bad programming practice?

  • 您似乎将对象序列化为字典;如果你想发回一个JSON对象,构造只包含Python对象第一个的东西,然后序列化整个。

  • 如果您需要自定义序列化逻辑(例如使用Django serialisation framework),请不要使用except装饰器重新编码,或者至少返回{{ 1}}实例以避免再次序列化