我們編寫一些接口函數(shù)的時候,經(jīng)常需要給調(diào)用者返回json格式的數(shù)據(jù),那么如何返回可直接解析的json格式的數(shù)據(jù)呢?
首先先來第一種方式:
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
import json
# Create your views here.
def index(request):
data={
'name':'zhangsan',
'age':18,
}
return HttpResponse(json.dumps(data))
訪問一下

通過訪問結(jié)果我們看到,在response的返回信息中,返回的Content-Type:是text/html,也就是字符串類型的返回,所以這段返回值并不是一個標(biāo)準(zhǔn)的json數(shù)據(jù),是一個長得像json數(shù)據(jù)的字符串,當(dāng)然可以通過工具直接轉(zhuǎn)換為json,不過既然是一個json的接口,那么我們拋出的數(shù)據(jù)自然是json格式的最好,那如何拋出標(biāo)準(zhǔn)json格式的數(shù)據(jù)呢?
稍稍修改一丟丟代碼,在HttpResponse中添加content_type類型為json的屬性
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
import json
# Create your views here.
def index(request):
data={
'name':'zhangsan',
'age':18,
}
return HttpResponse(json.dumps(data),content_type="application/json")

諾,這下返回的類型正常了
不過這里還是要提另外一個模塊JsonResponse,他內(nèi)置的幫我們封裝了這個轉(zhuǎn)換的操作,也就是說如果我們的接口拋json數(shù)據(jù)的話那么將HttpResponse替換為JsonResponse就OK啦
看一下JsonResponse的源代碼,其實也很簡單了,強制的幫你做了一下轉(zhuǎn)換,同時也支持了list的輸出
class JsonResponse(HttpResponse):
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
json_dumps_params=None, **kwargs):
if safe and not isinstance(data, dict):
raise TypeError(
'In order to allow non-dict objects to be serialized set the '
'safe parameter to False.'
)
if json_dumps_params is None:
json_dumps_params = {}
kwargs.setdefault('content_type', 'application/json')
data = json.dumps(data, cls=encoder, **json_dumps_params)
super(JsonResponse, self).__init__(content=data, **kwargs)
下邊我們來嘗試使用JsonResponse輸出一下dict和list
首先是dict
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
# Create your views here.
def index(request):
data={
'name':'zhangsan',
'age':18,
}
return JsonResponse(data)

下面看下list
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
# Create your views here.
def index(request):
listdata=[1,2,3,4,5]
return JsonResponse(listdata)
代碼改完后,訪問看輸出,結(jié)果發(fā)現(xiàn)報錯啦..為嘛?
TypeError at /mytest/hello/
In order to allow non-dict objects to be serialized set the safe parameter to False.
Request Method: GET
Request URL: http://10.89.0.5:8000/mytest/hello/
Django Version: 1.11.13
Exception Type: TypeError
Exception Value:
In order to allow non-dict objects to be serialized set the safe parameter to False.
Exception Location: /data/python36env/lib/python3.6/site-packages/django/http/response.py in __init__, line 524
Python Executable: /data/python36env/bin/python
Python Version: 3.6.4
Python Path:
['/vagrant/reboot_dj',
'/data/python36env/lib/python36.zip',
'/data/python36env/lib/python3.6',
'/data/python36env/lib/python3.6/lib-dynload',
'/usr/local/python36/lib/python3.6',
'/data/python36env/lib/python3.6/site-packages']
Server time: Mon, 4 Jun 2018 11:53:32 +0000
看這行的提示:In order to allow non-dict objects to be serialized set the safe parameter to False.
然后再看看JsonResponse的源代碼
if safe and not isinstance(data, dict):
raise TypeError(
'In order to allow non-dict objects to be serialized set the '
'safe parameter to False.'
)
是不是發(fā)現(xiàn)了什么?
嗯對,JsonResponse在拋出列表的時候需要將safe設(shè)置為False safe=False
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
# Create your views here.
def index(request):
listdata=[1,2,3,4,5]
return JsonResponse(listdata,safe=False)
修改完成后,再次訪問
