Django--json數據--JsonResponse模塊

from django.http import 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)
JsonResponse的好處是封裝和解封裝不用咱們本身封裝成json

 

 

補充:django

JsonResponse(["西遊記",'三國演義',"水滸傳"],safe=False)    #當序列化一個列表時,須要加參數safe=False
相關文章
相關標籤/搜索