簡體   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