网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

怎么在Django中返回json数据-创新互联

今天就跟大家聊聊有关怎么在Django中返回json数据,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

创新互联建站是专业的腾冲网站建设公司,腾冲接单;提供成都网站设计、成都网站建设,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行腾冲网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!

方法一:使用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看成是从数据库取出来的数据,使用浏览器访问一下testjson

怎么在Django中返回json数据

这不是乱码,这是中文在内存中的二进制表现形式而已,使用JSON的转换工具可以看到中文。

我们看一下Response Headers响应头,其中的Content-Typetext/html,我明明传的是JSON啊,怎么会变成字符串类型了?这是因为我们没有告诉浏览器,我们要传一个JSON数据,那么,怎么告诉浏览器呢?

def testjson(request):
 data={
  'patient_name': '张三',
  'age': '25',
  'patient_id': '19000347',
  '诊断': '上呼吸道感染',
 }
 return HttpResponse(json.dumps(data), content_type='application/json')

再访问网页:

怎么在Django中返回json数据

怎么在Django中返回json数据

现在是传输JSON了,在Preview中可以正常显示出来。

方法二:使用JsonResponse进行传输

def testjson(request):
 data={
  'patient_name': '张三',
  'age': '25',
  'patient_id': '19000347',
  '诊断': '上呼吸道感染',
 }
 return JsonResponse(data)

访问网页:

怎么在Django中返回json数据

怎么在Django中返回json数据

怎么在Django中返回json数据

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)

其内部也是通过json.dumps来把数据转换为JSON的,其还可以转换为list类型。我们再来改一下testjson

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

程序报错了

怎么在Django中返回json数据

报错为:In order to allow non-dict objects to be serialized set the safe parameter to False,它的意思是转换为一个非字典的类型时,safe参数要设置为False,还记得上面JsonResponse的原码吗?其中就有

怎么在Django中返回json数据

代码修改为:

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

怎么在Django中返回json数据

怎么在Django中返回json数据

怎么在Django中返回json数据

看完上述内容,你们对怎么在Django中返回json数据有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注创新互联行业资讯频道,感谢大家的支持。


当前题目:怎么在Django中返回json数据-创新互联
标题来源:http://bjjierui.cn/article/cdpise.html

其他资讯