Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django HttpResponse and unicode

I'm using django as the backend to a webapp. I'm sending json data via django and it has worked fine. However recently I have started dealing with non-ascii data and noticed some unusual behavior with the non-ascii characters. In my webapp I have code that looks like this:

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 doesn't have any problem with it, but when I view it in my browser (chrome), what I see is this:

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

Am I doing something wrong here? I have tried encoding the unicode object as utf-8 before giving it to HttpResponse() but it doesn't change anything.

Thanks for all the help!

like image 613
jmetz Avatar asked Jun 15 '13 23:06

jmetz


2 Answers

I figured this out. Hopefully anyone who has the same problem can google this.

The solution is to change the content_type to:

return HttpResponse(json_string, content_type='application/json; charset=utf-8')
like image 75
jmetz Avatar answered Nov 19 '22 10:11

jmetz


This is my contribution, return model serialize to json with UTF-8

    dptos = Departamento.objects.all()
    json_list = list(dptos.values())   
    return JsonResponse(json_list,safe=False,json_dumps_params={'ensure_ascii':False})
like image 39
Harold Meza Avatar answered Nov 19 '22 10:11

Harold Meza