久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

Django 返回json數(shù)據(jù)的實(shí)現(xiàn)示例

瀏覽:92日期:2024-05-29 09:18:10

在一個(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ù)庫取出來的數(shù)據(jù),使用瀏覽器訪問一下testjson

Django 返回json數(shù)據(jù)的實(shí)現(xiàn)示例

這不是亂碼,這是中文在內(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)頁:

Django 返回json數(shù)據(jù)的實(shí)現(xiàn)示例

Django 返回json數(shù)據(jù)的實(shí)現(xiàn)示例

現(xiàn)在是傳輸JSON了,在Preview中可以正常顯示出來。

方法二:使用JsonResponse進(jìn)行傳輸

def testjson(request): data={ ’patient_name’: ’張三’, ’age’: ’25’, ’patient_id’: ’19000347’, ’診斷’: ’上呼吸道感染’, } return JsonResponse(data)

訪問網(wǎng)頁:

Django 返回json數(shù)據(jù)的實(shí)現(xiàn)示例

Django 返回json數(shù)據(jù)的實(shí)現(xiàn)示例

Django 返回json數(shù)據(jù)的實(shí)現(xiàn)示例

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類型。我們再來改一下testjson

def testjson(request):listdata = ['張三', '25', '19000347', '上呼吸道感染']return JsonResponse(listdata)

程序報(bào)錯(cuò)了

Django 返回json數(shù)據(jù)的實(shí)現(xiàn)示例

報(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的原碼嗎?其中就有

Django 返回json數(shù)據(jù)的實(shí)現(xiàn)示例

代碼修改為:

def testjson(request): listdata = ['張三', '25', '19000347', '上呼吸道感染'] return JsonResponse(listdata, safe=False)

Django 返回json數(shù)據(jù)的實(shí)現(xiàn)示例

Django 返回json數(shù)據(jù)的實(shí)現(xiàn)示例

Django 返回json數(shù)據(jù)的實(shí)現(xiàn)示例

這有什么用

有時(shí)我們從數(shù)據(jù)庫取出來的數(shù)據(jù),很多是列表類型的,特別是用cx_Oracle包在Oracle數(shù)據(jù)庫取出來的數(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)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: JavaScript
相關(guān)文章:
主站蜘蛛池模板: 抚顺市| 电白县| 北票市| 田阳县| 禄丰县| 临汾市| 公安县| 合川市| 武功县| 双江| 伊宁县| 麻栗坡县| 九台市| 攀枝花市| 平阳县| 临沂市| 金平| 阿拉善左旗| 古蔺县| 四平市| 江油市| 来凤县| 佛坪县| 马鞍山市| 梓潼县| 楚雄市| 西藏| 隆子县| 孝昌县| 青川县| 贵州省| 麻江县| 独山县| 通山县| 五常市| 开原市| 温泉县| 溆浦县| 哈巴河县| 九龙城区| 剑阁县|