Skip to main content
 首页 » 编程设计

python之使用 Django 的 JSON Web 服务正确编码

2024年08月29日42wuhuacong

我正在构建一个 json 网络服务,其中包含带有 é、ñ、Á 等字符的字符串。

使用 python 我发现这段代码在控制台中运行时运行完美:

import json 
string = "NIÑO, ÁRBOL, HÉROE" 
print json_dumps({'string': string}, ensure_ascii=False, encoding='utf-8') 

问题是我使用的是 Django,它看起来不像上面的代码那么简单。这是我在 views.py 文件中所做的一瞥

import json 
from models import * 
from django.http import HttpResponse 
from django.db.models import Q 
 
def jsonService(request): 
    # The following line performs a query at the db 
    myObjects = MyObjects.objects().filter( Q(...) )  
 
    result = {"string": myObject[0].field } # let's say myObject[0].field contains "NIÑO, ÁRBOL, HÉROE" 
 
    # Prepares a response 
    response = HttpResponse(json.dumps(result, ensure_ascii=False, encoding="utf-8")) 
    # Sets the heades of content type and its charset 
    response['Content-type'] = 'application/json; charset=utf-8' 
 
    # Returns the response we prepared 
    return response 

这段代码的输出是:

{  
    string : "NIôO, ÃRBOL, HÃ%ROE" 
} 

如果我在组装结果对象时将 python 函数 repr() 应用于字符串 myObject[0].field,令我惊讶的是,结果是:

{  
    string : "NI\xc3\u2018O, \xc3\x81RBOL, H\xc3\u2030ROE" 
} 

我从这里可以推断出,数据库提供的字符串(根据 python 的 type() 是 unicode 字符串)可能是以 utf-8 以外的格式编码的,但它给我以下错误:

'ascii' codec can't decode byte 0xc3 in position 14: ordinal not in range 

那些转义字符对我来说似乎很奇怪,更不用说我不想要 unicode 字符串而是重音字符(类似于 {string: "NIÑO, ÁRBOL, HÉROE"}),我知道这是可能的,因为我'我已经看到一些谷歌服务使用口音。

一些建议?也许我在做一些我没有意识到的非常错误的事情,这就是为什么我描述了整个过程。

请您参考如下方法:

在你的 views.py 中尝试这个对我来说很好

from django.utils import simplejson 
from django.core.serializers.json import DjangoJSONEncoder 
 
def jsonService(request): 
 
    myObjects = MyObjects.objects().filter( Q(...) ) 
    fields = [x.field for x in myObjects] # creates a list of all fileds  
 
    # it will create JSON object 
    result=simplejson.dumps({ 
        'fileds':fileds, 
     }) 
 
    return HttpResponse(result, mimetype='application/json')