运维开发笔记整理-JsonResponse对象

          运维开发笔记整理-JsonResponse对象 

                                   作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

一.使用HttpResponse发送json格式的数据

1>.HttpResponse默认使用的是文本格式(text/html)

#!/usr/bin/env python
#_*_conding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/

from django.http import HttpResponse
import json
def index(request):
    data = {
        "name":"yinzhengjie",
        "age":"26",
    }

    return HttpResponse(json.dumps(data))

2>.使用HttpResponse传递json格式的数据

#!/usr/bin/env python
#_*_conding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/

from django.http import HttpResponse
import json
def index(request):
    data = {
        "name":"yinzhengjie",
        "age":"26",
    }

    return HttpResponse(json.dumps(data),content_type="application/json")

二.使用JsonResponse传递json格式的数据

1>.JsonResponse是继承HttpResponse

   注意,JsonResponse其实已经帮我们做了一些调优工作,如下图:

2>.使用JsonResponse传递json格式的数据

#!/usr/bin/env python
#_*_conding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/

from django.http import JsonResponse

def index(request):
    data = {
        "name":"yinzhengjie",
        "age":"26",
    }
    return JsonResponse(data)

原文地址:https://www.cnblogs.com/yinzhengjie/p/10245276.html