2

I'm building a json web service which contains strings with characters like é,ñ,Á,etc.

Using python I found this snippet of code that works perfectly when I run it in console:

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

The thing is that I'm using Django, and it doesn't look like it is as straightforward as the code above. Here's a peek of what I'm doing at my views.py file

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

The output of this code is:

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

if I apply python's function repr() to the string myObject[0].field when I assemble the result object, to my surprise the result is:

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

What I can infere from here is that maybe the strings that the db delivers (which are unicode strings acording to python's type()) are encoded in a format other that utf-8, but it thows me the following error:

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

Those escaped characters seems very strange to me, not to mention that I don't want unicode strings but the accented characters (something like {string: "NIÑO, ÁRBOL, HÉROE"}), I know it's possible because I've seen some google services work with accents.

Some advise? maybe I'm doing something incredibly wrong that I haven't realized, that's why I described the full process.

4

1 回答 1

3

Try this in your views.py works fine for me

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')
于 2012-12-17T04:41:28.970 回答