在django中输出utf-8个字符作为json

时间:2021-08-09 11:59:54

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.

我试图输出一些带有西里尔字符的json。但是,例如,而不是西里尔字母A我得到它的ascii代码 - \ u0410并不是json编码器打破了东西。如果我尝试输出ls变量本身,它已经显示ascii表示。尝试以不同的方式对其进行编码 - 解码,但最终得到了完全混乱。

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"}}

1 个解决方案

#1


7  

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.

用False替换以下行中的“False”。

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

#1


7  

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.

用False替换以下行中的“False”。

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