繁体   English   中英

django.http.JsonResponse以错误的格式返回json数据

[英]django.http.JsonResponse return json data in wrong format

我想返回queryset JSON格式,我用的是JsonResponse为以下几点:

def all_alert_history(request):
''' get all all alert history data '''
    all_data_json = serializers.serialize('json', LatestAlert.objects.all())
    return JsonResponse(all_data_json,safe=False)

但浏览器显示如下:

"[{\"fields\": {\"alert_name\": \"memory usage\", \"alert_value\": 83.7, \"alert_time\": \"2016-11-08T06:21:20.717Z\", \"alert_level\": \"warning\", \"alert_rule\": \"warning: > 80%\"}, \"model\": \"alert_handler.latestalert\", \"pk\": \"xyz.test-java.ip-10-0-10-138.memory.percent\"}]"

我用HttpResponse替换JsonResponse

def all_alert_history(request):
''' get all all alert history data '''
all_data_json = serializers.serialize('json', LatestAlert.objects.all())
return HttpResponse(all_data_json, content_type='application/json') 

浏览器显示如下:

[{"fields": {"alert_name": "memory usage", "alert_value": 83.7, "alert_time": "2016-11-08T06:21:20.717Z", "alert_level": "warning", "alert_rule": "warning: > 80%"}, "model": "alert_handler.latestalert", "pk": "xyz.test-java.ip-10-0-10-138.memory.percent"}]

所以,为什么在我使用JsonResponse时出现\\但在使用HttpResponse时消失?

django版本: 1.8

JsonResponse接受一个python字典并将其作为浏览器的json格式字符串返回。

由于您为JsonResponse提供了已经存在json格式的字符串,因此它将尝试使用\\来转义所有必需的字符。

例:

>>> from django.http import JsonResponse
>>> response = JsonResponse({'foo': 'bar'})
>>> response.content
b'{"foo": "bar"}'

在你的情况下, JsonResponse甚至会在传递字符串时警告你正在做什么,因此需要使用safe = False参数:

>>> mydata = {"asd":"bdf"}
>>> import json
>>> myjson = json.dumps(mydata)
>>> JsonResponse(myjson)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/swozny/work2/local/lib/python2.7/site-packages/django/http/response.py", line 500, in __init__
    raise TypeError('In order to allow non-dict objects to be '
TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False

将参数设置为False您观察到的行为是可重现的:

>>> JsonResponse(myjson,safe=False).content
'"{\\"asd\\": \\"bdf\\"}"'

底线是,如果你的模型比基本数据类型( IntegerFieldCharField ,...)稍微复杂一点,那么你可能会想要自己进行序列化并坚持使用HttpResponse或只使用djangorestframework ,它提供了工具来完成它您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM