Django return data using Json

In a Web site, a lot of data interaction with the front-end, JSON is the best way to transfer data.

In Django, JSON used to transmit data, there are two ways, one is to use the Python JSON packet, is to use the Django jsonResponse

Method a: JSON packet using Python

. 1  from django.shortcuts Import the HttpResponse
 2  
. 3  Import JSON
 . 4  
. 5  
. 6  DEF testjson (Request):
 . 7      Data = {
 . 8          ' patient_name ' : ' John Doe ' ,
 . 9          ' Age ' : ' 25 ' ,
 10          ' patient_id ' : ' 19,000,347 ' ,
 11          ' diagnosis ' : ' upper respiratory tract infection',
12     }
13     return HttpResponse(json.dumps(data))

Let us call data as the data is taken out from the database, using a browser to access it testjson

Hey, how is garbled? There are Chinese are garbled?

Do not worry, this is not garbage, it is Chinese binary representation in memory only, using JSON conversion tools can be seen in Chinese.

We look at the Response Headers response header, which the Content-Type is text / html, I obviously pass is JSON ah, how will become a string type? This is because we do not tell the browser, we have to pass a JSON data, then, how to tell the browser it?

HttpResponse inherited HttpResponseBase, we can tell the browser, I want to pass application / json data. We change a little bit the value of content and see what will become?

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

再访问网页:

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

 

方法二:使用JsonResponse进行传输。

1 def testjson(request):
2     data={
3         'patient_name': '张三',
4         'age': '25',
5         'patient_id': '19000347',
6         '诊断': '上呼吸道感染',
7     }
8     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

1 def testjson(request):
2     listdata = ["张三", "25", "19000347", "上呼吸道感染"]
3     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)

嗯,这下正常了。

这有什么用呢?有时我们从数据库取出来的数据,很多是列表类型的,特别是用cx_Oracle包在Oracle数据库取出来的数据,其不支持直接字典的输出,输出就是一个list,这时我们使用JsonResponse(data, safe=False)就可以直接输换为Json,发送到前端了。

 

Guess you like

Origin www.cnblogs.com/dhanchor/p/11122161.html