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

时间:2016-11-08 09:57:13

标签: python json django

我想以json格式返回queryset,我使用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\"}]"

我将JsonResponse替换为HttpResponse

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

1 个答案:

答案 0 :(得分:0)

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,...)稍微复杂一点,那么您可能希望自己进行序列化并坚持{ {1}}或者只使用提供工具的djangorestframework