使用djang正确编码JSON web服务

2024-09-30 08:28:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建一个jsonweb服务,它包含像é,ñ,Á等字符的字符串

在使用python时,我发现在console中运行的代码片段非常完美:

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

问题是我使用的是Django,看起来不像上面的代码那么简单。这是我在我的视图.py文件

^{pr2}$

此代码的输出为:

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

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

{ 
    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:“nininino,193; RBOL,HçROE”}),我知道这是可能的,因为我见过一些google服务使用重音符号。在

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


Tags: 字符串代码injsonstring错误asciiunicode
1条回答
网友
1楼 · 发布于 2024-09-30 08:28:28

试试这个视图.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')

相关问题 更多 >

    热门问题