如何让Django返回JsonResponse,没有额外的引号或引用转义? [英] How can I get Django to return JsonResponse with no extra quotes or quote escapes?

查看:1148
本文介绍了如何让Django返回JsonResponse,没有额外的引号或引用转义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Django 1.7,每当我在视图中返回以下位的JsonResponse:

  from django.http import JsonResponse 
token =1 $ aEJUhbdpO3cNrXUmFgvuR2SkXTP9 =
response = JsonResponse({token:token})
返回响应

我从Web浏览器/ cURL获取以下HTTP响应:

  {\token\:\1 $ aEJUhbdpO3cNrXUmFgvuR2SkXTP9 = \}

我想要的,Django 1.3中的内容是这样的:

  {token:1 $ aEJUhbdpO3cNrXUmFgvuR2SkXTP9 = 

我有两个依赖私有API使用Django的生产中的移动应用,不幸的是期待第二种响应,没有额外的引号(围绕整个JSON的报价使其成为一个字符串),没有引号转义。



我的问题是,是否有一些内置的方式来强制Django响应不能逃脱一个JSON响应?



我写了以下中间件来做,但...似乎是一个非常脆弱的暴力强制的方式:

  class UnescapeJSON(object):
def process_response(self,request,response):

在这里直接编辑响应对象,在html中搜索和替换条款


如果re.search('^ / api /.*',request.path):
r = response.content
r = r.replace('\
r = r.lstrip(''')
r = r.rstrip(''')
response.content = r
return response

所以我希望有一个更聪明的方式。



我正在尝试从Django 1.3更新旧的代码库到1.8,我目前在本地开发环境中的1.7版本,Django 1.3返回了正确的方式,没有额外的引号和反斜杠。 / p>

以这种方式返回JSON的一个好东西:

  { 令牌:1 $ aEJUhbdpO3cNrXUmFgvuR2SkXTP9 =} 

...是我正在使用 jQuery.post({success:...})来处理这个JSON响应,它自动运行 jQuery.parseJSON()为我,把它变成一个JSON对象我可以使用点符号进行访问。



我不能只是在客户端修复字符串并重新运行 parseJSON()手动,因为这将涉及让我的所有用户升级他们的移动应用程序。



所以我必须像上面那样获得JSON格式,或者我的移动API被有效地破坏。



我应该添加一点信息。这个API正在使用Django Piston :(我使用的是我发现的1.7x兼容版本,现在我不能在Django REST框架中交换卡,相信我,尽快可行。 p>

解决方案

我在1.8部署中看到了Django REST框架,最近刚从1.3增加到1.8,有一个RESTful支持,直到1.8,所以我不能声称这曾经工作(或没有工作)。



这个问题是由我创建的Python字典,序列化他们到JSON对象,然后在结果上调用json.dumps()。最后一步,调用json.dumps(),并将结果传递给Response()构造函数是导致一个用双引号包装的字符串。



更改我的代码:

  def get(self,request ,年,月,日,格式=无):
resp =无
日期= datetime(int(年),int(月),int(日),0,0)
临床ics = Clinic.objects.all()
for x in clinics:
aDate = datetime(x.date.year,x.date.month,x.date.day)
如果日期> = aDate和date< = aDate + timedelta(days = x.duration):
resp = serializers.serialize(json,[x,])
struct = json.loads )
struct [0] [fields] [id] = x.id
resp = json.dumps(struct [0] [fields])
break

如果resp ==无:
raise NotFound()
返回响应(resp)

  def get(self,request,year,month,day,format = :
resp =无
date = datetime(int(year),int(month),int(day),0,0)
clinics = Clinic.objects.all()
for x in clinics:
aDate = datetime(x.date.year,x.date.month,x.date.day)
如果date> = aDate和date< = aDate + timedelta(days = x.duration):
resp = serializers.seriali ze(json,[x,])
struct = json.loads(resp)
struct [0] [fields] [id] = x.id
= struct [0] [fields]
break

如果resp ==无:
raise NotFound()
返回响应(resp)
在Django REST中修复问题(对我来说)

(注意,我分配的行是唯一需要更改的行)。希望这有所帮助。


Using Django 1.7, whenever I return the following bit of JsonResponse in a view:

from django.http import JsonResponse
token = "1$aEJUhbdpO3cNrXUmFgvuR2SkXTP9="
response = JsonResponse({"token": token})
return response

I'm getting the following HTTP response from web browser/cURL:

"{\"token\": \"1$aEJUhbdpO3cNrXUmFgvuR2SkXTP9=\"}"

What I want, and what I had in Django 1.3 was this:

{"token": "1$aEJUhbdpO3cNrXUmFgvuR2SkXTP9="}

I have two mobile apps in production that rely on a private API using Django, and unfortunately they are expecting the second kind of response, with no extra quotes (the quote that surround the entire JSON making it a string) and no quote escapes.

My question is, is there some built-in way to force Django response to not escape a JSON response?

I wrote the following middleware to do it, but...it seems like a really fragile brute force way of going about it:

class UnescapeJSON(object):
    def process_response(self, request, response):
        """
        Directly edit response object here, searching for and replacing terms
        in the html.
        """
        if re.search('^/api/.*', request.path):
            r = response.content
            r = r.replace('\\', '')
            r = r.lstrip('"')
            r = r.rstrip('"')
            response.content = r
        return response

So I'm hoping there is a smarter way.

Backstory is I'm trying to update an old legacy code base from Django 1.3 to 1.8. I currently have it on 1.7 in my local dev environment. Django 1.3 returned the JSON the correct way, without extra quotes and backslashes.

One nice thing about returning the JSON in this way:

{"token": "1$aEJUhbdpO3cNrXUmFgvuR2SkXTP9="}

...is that I'm using jQuery.post({success:...}) to handle this JSON response, and it automatically runs jQuery.parseJSON() for me, turning it into a JSON object I can access with dot notation.

I can't just fix string on the client side and re-run parseJSON() manually, because that would involve getting all my users to upgrade their mobile app.

So I have to get JSON formatted as above, or my mobile API is effectively broken.

One bit of info I should add. This API is using Django Piston :(. I'm using a 1.7x compatible version I found. It's not in the cards for me to swap in Django REST Framework right now. Believe me, I will as soon as feasibly possible.

解决方案

I was seeing this with Django REST Framework in a 1.8 deployment. I just went from 1.3 to 1.8 recently. However, I didn't have RESTful support until 1.8 so I can't claim this ever worked (or didn't work).

The problem was caused by my creating Python dictionaries, serializing them to JSON objects, and then calling json.dumps() on the result. The last step, calling json.dumps(), and passing the result to the Response() constructor is what led to a string that got wrapped with double quotes.

Changing my code from:

def get(self, request, year, month, day, format=None):
    resp = None
    date = datetime(int(year), int(month), int(day), 0, 0)
    clinics = Clinic.objects.all()
    for x in clinics:
        aDate = datetime(x.date.year, x.date.month, x.date.day)
        if date >= aDate and date <= aDate + timedelta(days=x.duration):
            resp = serializers.serialize("json", [x, ])
            struct = json.loads(resp)
            struct[0]["fields"]["id"] = x.id
            resp = json.dumps(struct[0]["fields"])
            break

    if resp == None:
        raise NotFound()
    return Response(resp)

to

def get(self, request, year, month, day, format=None):
    resp = None
    date = datetime(int(year), int(month), int(day), 0, 0)
    clinics = Clinic.objects.all()
    for x in clinics:
        aDate = datetime(x.date.year, x.date.month, x.date.day)
        if date >= aDate and date <= aDate + timedelta(days=x.duration):
            resp = serializers.serialize("json", [x, ])
            struct = json.loads(resp)
            struct[0]["fields"]["id"] = x.id
            resp = struct[0]["fields"]
            break

    if resp == None:
        raise NotFound()
    return Response(resp)

fixed the problem (for me) in Django REST. (Note, the line where I assign resp is the only one that needed changing). Hope this helps somehow.

这篇关于如何让Django返回JsonResponse,没有额外的引号或引用转义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆