今天就跟大家聊聊有关怎么在Django中返回json数据,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
方法一:使用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
这不是乱码,这是中文在内存中的二进制表现形式而已,使用JSON的转换工具可以看到中文。
我们看一下Response Headers响应头,其中的Content-Type
是text/html
,我明明传的是JSON啊,怎么会变成字符串类型了?这是因为我们没有告诉浏览器,我们要传一个JSON数据,那么,怎么告诉浏览器呢?
def testjson(request):
data={
'patient_name': '张三',
'age': '25',
'patient_id': '19000347',
'诊断': '上呼吸道感染',
}
return HttpResponse(json.dumps(data), content_type='application/json')
再访问网页:
现在是传输JSON了,在Preview中可以正常显示出来。
方法二:使用JsonResponse进行传输
def testjson(request):
data={
'patient_name': '张三',
'age': '25',
'patient_id': '19000347',
'诊断': '上呼吸道感染',
}
return JsonResponse(data)
访问网页:
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)
程序报错了
报错为:In order to allow non-dict objects to be serialized set the safe parameter to False
,它的意思是转换为一个非字典的类型时,safe参数要设置为False,还记得上面JsonResponse的原码吗?其中就有
代码修改为:
def testjson(request):
listdata = ["张三", "25", "19000347", "上呼吸道感染"]
return JsonResponse(listdata, safe=False)
看完上述内容,你们对怎么在Django中返回json数据有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。