如何在tasypie结果中解码unicode字符串

时间:2015-07-03 09:39:26

标签: json django unicode utf-8 tastypie

我有一些基于django和django-tastypie的REST应用程序

class CompanyResource(BaseResource):

    class Meta:

        queryset =      Company.objects.all()
        resource_name = 'company/company'
        allowed_mathods=('get', 'path')
        filtering = {
            'id':       ALL,
            'category': ALL_WITH_RELATIONS,
            'name':     ('exact', 'icontains'),
            'synonyms': ('icontains', ),
        }

工作正常。响应如下:

{
    "meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 2}, 
    "objects": [{"_active": true, "name": "Рога и копыта"}]
}

但是当我尝试自定义结果时:

def get_list(self, request, **kwargs):
    resp = super(CompanyResource, self).get_list(request, **kwargs)

    data = json.loads(resp.content)

    if request.GET.get('query', False) :

        query = request.GET.get('query')
        reg_query = re.escape(query)

        for i, object in enumerate(data['objects']):

            # some logic here
            data['objects'][i]['blah-bla-blah'] = query.split()

    data = json.dumps(data, encoding='utf-8',)

    return HttpResponse(data, content_type='application/json', status=200)

我看到响应中的unicode转义字符串

{
    "meta": ..., 
    "objects": [{"_active": true, "name": "\u0420\u043e\u0433\u0430 \u0438 \u043a\u043e\u043f\u044b\u0442\u0430", "blah-bla-blah": "blah-blah-blah_data"}]
}

如何使用UTF字符串返回数据?

0 个答案:

没有答案