Django 返回json數(shù)據(jù)的實(shí)現(xiàn)示例
在一個(gè)網(wǎng)站,大量數(shù)據(jù)的前后端交互,JSON是最好的傳遞數(shù)據(jù)方式了。在Django中,使用JSON傳輸數(shù)據(jù),有兩種方式,一種是使用Python的JSON包,一種是使用Django的JsonResponse
方法一:使用Python的JSON包
from django.shortcuts import HttpResponseimport jsondef testjson(request): data={ ’patient_name’: ’張三’, ’age’: ’25’, ’patient_id’: ’19000347’, ’診斷’: ’上呼吸道感染’, } return HttpResponse(json.dumps(data))
我們暫且把data看成是從數(shù)據(jù)庫(kù)取出來的數(shù)據(jù),使用瀏覽器訪問一下testjson
這不是亂碼,這是中文在內(nèi)存中的二進(jìn)制表現(xiàn)形式而已,使用JSON的轉(zhuǎn)換工具可以看到中文。
我們看一下Response Headers響應(yīng)頭,其中的Content-Type是text/html,我明明傳的是JSON啊,怎么會(huì)變成字符串類型了?這是因?yàn)槲覀儧]有告訴瀏覽器,我們要傳一個(gè)JSON數(shù)據(jù),那么,怎么告訴瀏覽器呢?
def testjson(request): data={ ’patient_name’: ’張三’, ’age’: ’25’, ’patient_id’: ’19000347’, ’診斷’: ’上呼吸道感染’, } return HttpResponse(json.dumps(data), content_type=’application/json’)
再訪問網(wǎng)頁(yè):
現(xiàn)在是傳輸JSON了,在Preview中可以正常顯示出來。
方法二:使用JsonResponse進(jìn)行傳輸
def testjson(request): data={ ’patient_name’: ’張三’, ’age’: ’25’, ’patient_id’: ’19000347’, ’診斷’: ’上呼吸道感染’, } return JsonResponse(data)
訪問網(wǎng)頁(yè):
JsonResponse的源碼
class JsonResponse(HttpResponse): ''' An HTTP response class that consumes data to be serialized to JSON. :param data: Data to be dumped into json. By default only ``dict`` objects are allowed to be passed due to a security flaw before EcmaScript 5. See the ``safe`` parameter for more information. :param encoder: Should be a json encoder class. Defaults to ``django.core.serializers.json.DjangoJSONEncoder``. :param safe: Controls if only ``dict`` objects may be serialized. Defaults to ``True``. :param json_dumps_params: A dictionary of kwargs passed to json.dumps(). ''' 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().__init__(content=data, **kwargs)
其內(nèi)部也是通過json.dumps來把數(shù)據(jù)轉(zhuǎn)換為JSON的,其還可以轉(zhuǎn)換為list類型。我們?cè)賮砀囊幌聇estjson
def testjson(request):listdata = ['張三', '25', '19000347', '上呼吸道感染']return JsonResponse(listdata)
程序報(bào)錯(cuò)了
報(bào)錯(cuò)為:In order to allow non-dict objects to be serialized set the safe parameter to False,它的意思是轉(zhuǎn)換為一個(gè)非字典的類型時(shí),safe參數(shù)要設(shè)置為False,還記得上面JsonResponse的原碼嗎?其中就有
代碼修改為:
def testjson(request): listdata = ['張三', '25', '19000347', '上呼吸道感染'] return JsonResponse(listdata, safe=False)
這有什么用
有時(shí)我們從數(shù)據(jù)庫(kù)取出來的數(shù)據(jù),很多是列表類型的,特別是用cx_Oracle包在Oracle數(shù)據(jù)庫(kù)取出來的數(shù)據(jù),其不支持直接字典的輸出,輸出就是一個(gè)list,這時(shí)我們使用JsonResponse(data, safe=False)就可以直接輸換為Json,發(fā)送到前端了。
到此這篇關(guān)于Django 返回json數(shù)據(jù)的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)Django返回json 內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python selenium 獲取接口數(shù)據(jù)的實(shí)現(xiàn)2. java 優(yōu)雅關(guān)閉線程池的方案3. 詳解idea中web.xml默認(rèn)版本問題解決4. asp知識(shí)整理筆記4(問答模式)5. jsp實(shí)現(xiàn)textarea中的文字保存換行空格存到數(shù)據(jù)庫(kù)的方法6. ASP實(shí)現(xiàn)加法驗(yàn)證碼7. jsp EL表達(dá)式詳解8. Python matplotlib 繪制雙Y軸曲線圖的示例代碼9. 利用ajax+php實(shí)現(xiàn)商品價(jià)格計(jì)算10. JSP頁(yè)面實(shí)現(xiàn)驗(yàn)證碼校驗(yàn)功能
