django HttpResponse和unicode

jme*_*etz 2 django unicode json non-ascii-characters

我正在使用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')
Run Code Online (Sandbox Code Playgroud)

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

{"start_location" : "5802 W 71st St Indianapolis‎ Indiana‎ 46278 United States", "lat" : 39.8819269, "lng" : -86.2631006, "timezone" : "America/Indiana/Indianapolis"}
Run Code Online (Sandbox Code Playgroud)

我在这里做错了吗?我已经尝试将unicode对象编码为utf-8,然后将其提供给HttpResponse(),但它不会改变任何东西.

感谢您的帮助!

jme*_*etz 8

我想通了.希望任何有相同问题的人都可以谷歌这个.

解决方案是将content_type更改为:

return HttpResponse(json_string, content_type='application/json; charset=utf-8')
Run Code Online (Sandbox Code Playgroud)


Har*_*eza 6

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

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