美文网首页程序员
Django如何输出Json数据

Django如何输出Json数据

作者: Real_man | 来源:发表于2018-11-20 08:10 被阅读303次

Django1.7版本加入了JsonResponse类,它是HttpResponse的子类,它默认的Content-Type头部为 application/json,同时它自己内部也有JSON encoder,这样我们就不用再返回响应的时候自己再序列化数据。

image.png

一个小案例:

from django.http.response import JsonResponse

def index(request):
    data = {
        'name': 'Vitor',
        'location': 'Finland',
        'is_active': True,
        'count': 28
    }
    return JsonResponse(data)
image

默认情况下JsonResponse的第一个参数必须是字典类型的数据,如果是非字典型的,必须要设置第二个参数safeFalse

加入将刚才的data换为数组:报如下错误

def index(request):
    list_data = [1,2,3,4]
    return JsonResponse(list_data)
image

JsonResponse内部结构

从代码中进入JsonResponse类,可以看到其实现如下:

class JsonResponse(HttpResponse):
    """
     data 要被序列化的数据
     encoder 默认是django.core.serializers.json.DjangoJSONEncoder
     safe 控制是否只有字典类型的数据才能被序列化
     json_dumps_params用于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)

其参数:

  • data 要被序列化的数据
  • encoder 默认是django.core.serializers.json.DjangoJSONEncoder
  • safe 控制是否只有字典类型的数据才能被序列化
  • json_dumps_params用于json_dumps是传递的参数

返回模型数据为Json类型

如果想返回Django模型类的数据为JSON,那么做法如下:

记得将对象转换为list类型。

def index(request):
    question = Question.objects.all().values()
    qu_list = list(question)
    return JsonResponse(qu_list,safe=False)
image

最后

Json作为现在网络传输中的通用格式,不管何种语言,它的序列化都是很重要的,希望能帮助大家。

参考

https://simpleisbetterthancomplex.com/tutorial/2016/07/27/how-to-return-json-encoded-response.html
https://stackoverflow.com/questions/9262278/django-view-returning-json-without-using-template

相关文章

网友评论

    本文标题:Django如何输出Json数据

    本文链接:https://www.haomeiwen.com/subject/fjxtqqtx.html