使用django的JSON Web服务正确编码

时间:2012-12-16 22:30:01

标签: python django json character-encoding

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

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

我可以从这里得到的结论是,db可能传递的字符串(根据python的type()是unicode字符串)以utf-8的格式编码,但是它给我带来了以下错误:< / p>

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

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

有人建议吗?也许我正在做一些我没有意识到的令人难以置信的错误,这就是我描述完整过程的原因。

1 个答案:

答案 0 :(得分:3)

在你的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')