Django中使用Json返回?cái)?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ì)變成字符串類型了?這是因?yàn)槲覀儧](méi)有告訴瀏覽器,我們要傳一個(gè)JSON數(shù)據(jù),那么,怎么告訴瀏覽器呢?
HttpResponse是繼承HttpResponseBase的,我們可以告訴瀏覽器,我要傳application/json數(shù)據(jù)。我們稍微改一下content的值,看看會(huì)變成什么?
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è):
這下好了,是傳輸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類型。我們?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è)非字典的類型時(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ù),很多是列表類型的,特別是用cx_Oracle包在Oracle數(shù)據(jù)庫(kù)取出來(lái)的數(shù)據(jù),其不支持直接字典的輸出,輸出就是一個(gè)list,這時(shí)我們使用JsonResponse(data, safe=False)就可以直接輸換為Json,發(fā)送到前端了。
到此這篇關(guān)于Django中使用Json返回?cái)?shù)據(jù)的實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān)Django Json返回?cái)?shù)據(jù)內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. XML 增、刪、改和查示例2. SXNA RSS Blog 聚合器程序3. ASP動(dòng)態(tài)網(wǎng)頁(yè)制作技術(shù)經(jīng)驗(yàn)分享4. jsp實(shí)現(xiàn)登錄驗(yàn)證的過(guò)濾器5. 淺談SpringMVC jsp前臺(tái)獲取參數(shù)的方式 EL表達(dá)式6. JSP的Cookie在登錄中的使用7. ASP常用日期格式化函數(shù) FormatDate()8. jsp實(shí)現(xiàn)textarea中的文字保存換行空格存到數(shù)據(jù)庫(kù)的方法9. webpack高級(jí)配置與優(yōu)化詳解10. PHP設(shè)計(jì)模式中工廠模式深入詳解
