溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在Django中返回json數(shù)據(jù)

發(fā)布時間:2021-04-06 16:16:39 來源:億速云 閱讀:392 作者:Leah 欄目:開發(fā)技術(shù)

今天就跟大家聊聊有關(guān)怎么在Django中返回json數(shù)據(jù),可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

方法一:使用Python的JSON包

from django.shortcuts import HttpResponse
import json

def 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ù)

這不是亂碼,這是中文在內(nèi)存中的二進(jìn)制表現(xiàn)形式而已,使用JSON的轉(zhuǎn)換工具可以看到中文。

我們看一下Response Headers響應(yīng)頭,其中的Content-Typetext/html,我明明傳的是JSON啊,怎么會變成字符串類型了?這是因為我們沒有告訴瀏覽器,我們要傳一個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ù)

怎么在Django中返回json數(shù)據(jù)

現(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ù)

怎么在Django中返回json數(shù)據(jù)

怎么在Django中返回json數(shù)據(jù)

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)

程序報錯了

怎么在Django中返回json數(shù)據(jù)

報錯為:In order to allow non-dict objects to be serialized set the safe parameter to False,它的意思是轉(zhuǎn)換為一個非字典的類型時,safe參數(shù)要設(shè)置為False,還記得上面JsonResponse的原碼嗎?其中就有

怎么在Django中返回json數(shù)據(jù)

代碼修改為:

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

怎么在Django中返回json數(shù)據(jù)

怎么在Django中返回json數(shù)據(jù)

怎么在Django中返回json數(shù)據(jù)

看完上述內(nèi)容,你們對怎么在Django中返回json數(shù)據(jù)有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI