Django之JsonResponse

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 an json encoder class. Defaults to
      ``django.core.serializers.json.DjangoJSONEncoder``.
    :param safe: Controls if only ``dict`` objects may be serialized. Defaults
      to ``True``.
    """

    def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, **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')
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder)
        super(JsonResponse, self).__init__(content=data, **kwargs)

1: JsonResponse是HttpResponse的子类, 它的默认Content-Type被设置为: application/json

2: 第一个参数, data应该是一个字典类型, 当safe这个参数被设置为:False, 那data可以填入任何能被转换为JSON格式的对象, 比如list, tuple, set。默认的safe参数是True, 如果你传入的data数据类型不是字典类型, 那么它就会抛出TypeError的异常。

3: json_dumps_params参数是一个字典,它将调用json.dumps()方法并将字典中的参数传入给该方法。

JsonResponse与HttpResponse的比较
在返回json数据时

1: 如果这样返回,ajax还需要进行json解析
# views.py中
return HttpResponse(json.dumps({"msg": "OK"}))

# index.html
var data = json.parse(data)
console.log(data.msg)


2: 如果这样返回,两边都不需要进行json的序列化与反序列化,ajax接受的直接是一个对象
# views.py
from django.http import JsonResponse
return JsonResponse({"msg": "OK"})

# index.html
console.log(data.msg)

你可能感兴趣的:(Django之JsonResponse)