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ù)取出來(lái)的數(shù)據(jù),使用瀏覽器訪問(wèn)一下testjson
這不是亂碼,這是中文在內(nèi)存中的二進(jìn)制表現(xiàn)形式而已,使用JSON的轉(zhuǎn)換工具可以看到中文。
我們看一下Response Headers響應(yīng)頭,其中的Content-Type是text/html,我明明傳的是JSON啊,怎么會(huì)變成字符串類(lèi)型了?這是因?yàn)槲覀儧](méi)有告訴瀏覽器,我們要傳一個(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èn)網(wǎng)頁(yè):
現(xiàn)在是傳輸JSON了,在Preview中可以正常顯示出來(lái)。
方法二:使用JsonResponse進(jìn)行傳輸
def testjson(request): data={ ’patient_name’: ’張三’, ’age’: ’25’, ’patient_id’: ’19000347’, ’診斷’: ’上呼吸道感染’, } return JsonResponse(data)
訪問(wèn)網(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)部也是通過(guò)json.dumps來(lái)把數(shù)據(jù)轉(zhuǎn)換為JSON的,其還可以轉(zhuǎn)換為list類(lèi)型。我們?cè)賮?lái)改一下testjson
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è)非字典的類(lèi)型時(shí),safe參數(shù)要設(shè)置為False,還記得上面JsonResponse的原碼嗎?其中就有
代碼修改為:
def testjson(request): listdata = ['張三', '25', '19000347', '上呼吸道感染'] return JsonResponse(listdata, safe=False)
這有什么用
有時(shí)我們從數(shù)據(jù)庫(kù)取出來(lái)的數(shù)據(jù),很多是列表類(lèi)型的,特別是用cx_Oracle包在Oracle數(shù)據(jù)庫(kù)取出來(lái)的數(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. XML入門(mén)的常見(jiàn)問(wèn)題(一)2. Jsp中request的3個(gè)基礎(chǔ)實(shí)踐3. 怎樣才能用js生成xmldom對(duì)象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?4. IntelliJ IDEA 統(tǒng)一設(shè)置編碼為utf-8編碼的實(shí)現(xiàn)5. Django ORM實(shí)現(xiàn)按天獲取數(shù)據(jù)去重求和例子6. jsp EL表達(dá)式詳解7. idea給項(xiàng)目打war包的方法步驟8. chat.asp聊天程序的編寫(xiě)方法9. idea修改背景顏色樣式的方法10. idea設(shè)置自動(dòng)導(dǎo)入依賴(lài)的方法步驟
