【问题标题】:How do I remove the "u" prefix from a (json serialized) list of dictionaries?如何从(json 序列化)字典列表中删除“u”前缀?
【发布时间】: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


【解决方案1】:

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

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

然后两次:

data = simplejson.dumps(str(objects))

这对从视图函数返回的objectsstr() 表示进行编码,然后将其转换为 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>\'}"'

您的装饰器还有几个问题:

  • 您正在使用毯子except 处理程序,因此您正在掩盖第一次尝试使用simplejson.dumps() 进行序列化时抛出的任何错误。永远不要使用毯子except 并让异常静音。你现在不知道那里出了什么问题。另见Why is "except: pass" a bad programming practice?

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

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

【讨论】:

  • 三次;他们不只是dumps(objects),他们也打电话给str
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-30
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 2023-02-10
  • 2020-07-14
  • 1970-01-01
相关资源
最近更新 更多