Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output utf-8 characters in django as json

I am trying to output some json with cyrillic characters in it. But, for instance, instead of cyrillic A I get it's ascii code - \u0410 And it is not json encoder that breaks the stuff. If I try to output the ls variable itself, it already shows ascii representation. Tried to encode-decode it in different ways, but got compeletly messed in the end.

Here is the code:

def grades(request):
grades = Grades.objects.all()

Status = 0
Message = 'No records'
dataset = {}
Response = {}
Response['Type'] = 'class'
Response['Data'] = {}
x = ''

if grades.exists() :
    Status = 1
    Message = 'Success'
    ls = list()
    for grade in grades:
        dataitem = {}
        dataitem['id'] = grade.id
        dataitem['name'] = u'' + str(grade.grade) +  grade.letter
        #x = x + 
        ls.append( dataitem )
    Response['Data'] = ls

dataset['Status'] = Status
dataset['Message'] = Message
dataset['Response'] = Response

return HttpResponse(json.dumps(dataset, ensure_ascii="False"), content_type="application/json; encoding=utf-8")

Here is the output:

{"Status": 1, "Message": "Success", "Response": 
{"Data": [{"id": 1, "name": "1\u0410"}, 
{"id": 2, "name": "1\u0411"}, 
{"id": 3, "name": "1\u0412"}, 
{"id": 4, "name": "2\u0410"}, 
{"id": 5, "name": "2\u0411"}, 
{"id": 6, "name": "2\u0412"}], "Type": "class"}}
like image 364
Lexx.KG Avatar asked Dec 18 '13 12:12

Lexx.KG


1 Answers

Non-empty string is treated as true value.

>>> bool("False")
True
>>> bool("")
False

>>> print(json.dumps(u'\u0411', ensure_ascii="False"))
"\u0411"
>>> print(json.dumps(u'\u0411', ensure_ascii=False))
"Б"

Replace "False" in the following line with False.

return HttpResponse(json.dumps(dataset, ensure_ascii="False"), content_type="application/json; encoding=utf-8")
#                                                    ^^^^^^^ to False
like image 126
falsetru Avatar answered Oct 23 '22 02:10

falsetru