十一、Django学习之返回json数据

后端现在返回的数据格式经常要求是json的,可以使用JsonResponse返回json格式数据。

class JsonResponse(HttpResponse):
    """
    :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().
    """
'''
    data: 应该传递一个标准的 python 字典给它,它将其转换成 json 格式的数据。
 
  encoder:默认为 django.core.serializers.json.DjangoJSONEncoder,用于序列化data。关于这个序列化的更多信息参见JSON 序列化。
 
  safe : 默认为True。如果设置为False,可以传递任何对象进行序列化(否则,只允许dict 实例)。如果safe 为True,而第一个参数传递的不是dict 对象,
将抛出一个TypeError。另外:它的默认 Content-Type 头部设置为application/json。   json_dumps_params:可以传递一个python标准的 json 库中,json.dump() 方法处理后的对象给它,用于生成一个响应。 ''' 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)

views.py代码:

def get_json(request):

    hero = Hero.objects.all()
    data = {}

    res1 = serializers.serialize("json",hero)
    print(res1,type(res1))

    data["result"] = json.loads(res1)
    print(data)


    return JsonResponse(data,safe=False,json_dumps_params={'ensure_ascii':True})

结果:

{
    "result":[
        {
            "model":"vote.hero",
            "pk":9,
            "fields":{
                "name":"武松",
                "propertys":"大刀",
                "is_male":true,
                "power":2,
                "time_stamp":"2020-03-12T00:00:00Z"
            }
        },
        {
            "model":"vote.hero",
            "pk":10,
            "fields":{
                "name":"牛郎",
                "propertys":"长剑",
                "is_male":false,
                "power":4,
                "time_stamp":"2020-03-12T00:00:00Z"
            }
        },
        {
            "model":"vote.hero",
            "pk":11,
            "fields":{
                "name":"战狼",
                "propertys":"丛林作战",
                "is_male":true,
                "power":1,
                "time_stamp":"2020-03-13T00:00:00Z"
            }
        },
        {
            "model":"vote.hero",
            "pk":12,
            "fields":{
                "name":"宋江",
                "propertys":"大刀",
                "is_male":true,
                "power":3,
                "time_stamp":"2020-03-13T00:00:00Z"
            }
        },
        {
            "model":"vote.hero",
            "pk":13,
            "fields":{
                "name":"宋江",
                "propertys":"大刀",
                "is_male":true,
                "power":3,
                "time_stamp":"2020-03-13T00:00:00Z"
            }
        }
    ]
}

 

上一篇:30. Django 2.1.7 模板 - HTML转义


下一篇:day99-django-避免xss攻击