Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用django对JSON web服务进行正确编码_Python_Django_Json_Character Encoding - Fatal编程技术网

Python 使用django对JSON web服务进行正确编码

Python 使用django对JSON web服务进行正确编码,python,django,json,character-encoding,Python,Django,Json,Character Encoding,我正在构建一个json web服务,其中包含带有诸如é、ñ、Á等字符的字符串 使用python,我发现这段代码在console中运行时效果非常好: import json string = "NIÑO, ÁRBOL, HÉROE" print json_dumps({'string': string}, ensure_ascii=False, encoding='utf-8') 问题是我使用的是Django,它看起来不像上面的代码那么简单。下面是我在我的views.py文件中所做工作的一个概览

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

使用python,我发现这段代码在console中运行时效果非常好:

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]。字段,那么结果会是:

{ 
    string : "NI\xc3\u2018O, \xc3\x81RBOL, H\xc3\u2030ROE"
}
从这里我可以推断出,db传递的字符串(根据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”),我知道这是可能的,因为我看到一些google服务使用重音


有什么建议吗?也许我做了一些我没有意识到的难以置信的错误,这就是为什么我描述了整个过程

在你的视图中试试这个。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')

您确认数据库正在使用utf-8吗?mySQL在默认情况下不会这样做。@AgDude我不确定这是怎么回事。我用一个python脚本填充数据库,在打开连接时指定了编码utf-8,在我将数据库上传到我的服务器heroku btw时,我也指定了相同的编码。对我的dbm应用一些特殊的配置行吗?我没有使用heroku,但是请检查。一如既往,如果要更改现有数据库,请先进行备份@AgDude在修改heroku的配置之前,我用
heroku config
查询当前的on,默认值已经是
en_US.UTF-8
,我改为
es_es.UTF-8
,服务器自动重启,但什么也没有。我一直在研究这个“\xc3”字符,也许它是以前编码的残余,但还不确定。看起来它是从数据库中出来的,已经不正确了。使用pdb.set_trace()在python shell中使用runserver查看对象。数据是如何插入数据库的?你能直接在SQL客户机中查看数据吗?如果我使用这个方法,我会得到与使用json时相同的结果
{string:“NIÃO,ÃRBOL,HÃ%ROE”}
。但是我担心可能缺少了一些东西,因为DjangoJSONEncoder没有使用它,是吗?我对这种方法非常乐观,因为一位同事建议我也使用simplejson。