【问题标题】:django HttpResponse and unicodedjango HttpResponse 和 unicode
【发布时间】:2013-06-12 07:14:43
【问题描述】:

我使用 django 作为 webapp 的后端。我正在通过 django 发送 json 数据,它运行良好。但是最近我开始处理非 ascii 数据,并注意到非 ascii 字符的一些异常行为。在我的 webapp 中,我的代码如下所示:

def make_json():
  json_string = u{"start_location" : "5802 W 71st St Indianapolis‎ Indiana‎ 46278 United States", "lat" : 39.8819269, "lng" : -86.2631006, "timezone" : "America/Indiana/Indianapolis"}
  return HttpResponse(json_string, content_type='application/json')

Django 没有任何问题,但是当我在浏览器(chrome)中查看它时,我看到的是:

{"start_location" : "5802 W 71st St Indianapolis‎ Indiana‎ 46278 United States", "lat" : 39.8819269, "lng" : -86.2631006, "timezone" : "America/Indiana/Indianapolis"}

我在这里做错了吗?在将 unicode 对象提供给 HttpResponse() 之前,我尝试将其编码为 utf-8,但它并没有改变任何东西。

感谢大家的帮助!

【问题讨论】:

    标签: django json unicode non-ascii-characters


    【解决方案1】:

    这是我的贡献,返回模型序列化为 UTF-8 的 json

        dptos = Departamento.objects.all()
        json_list = list(dptos.values())   
        return JsonResponse(json_list,safe=False,json_dumps_params={'ensure_ascii':False})
    

    【讨论】:

      【解决方案2】:

      我想通了。希望有同样问题的朋友可以google一下。

      解决方法是将content_type改为:

      return HttpResponse(json_string, content_type='application/json; charset=utf-8')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-31
        • 2010-12-04
        • 2011-12-28
        • 2011-04-08
        • 1970-01-01
        • 1970-01-01
        • 2011-04-10
        相关资源
        最近更新 更多