zoukankan      html  css  js  c++  java
  • Python

    用 json 模块和 HttpResponse 返回生成的 json

    views.py:

    from django.shortcuts import render, HttpResponse
    import json
    
    # json 测试
    def json_test(request):
        data = {"name": "Jack", "age": 18}
        hobby = ["Music", "Movie", "Basketball", "Reading"]  
        json_data = json.dumps(data)       # 把 data 序列化成 json 格式的字符串
        # json_data = json.dumps(hobby)  # 该方法也可以直接序列化列表
        return HttpResponse(json_data)
    

    运行结果:

    JsonResponse 是 HttpResponse 的子类,用来生成 json 编码的响应

    views.py:

    from django.shortcuts import render, HttpResponse
    
    # json 测试
    def json_test(request):
        data = {"name": "Jack", "age": 18}
        hobby = ["Music", "Movie", "Basketball", "Reading"]
        # 这里需要导入 HttpResponse
        from django.http import HttpResponse, JsonResponse
        return JsonResponse(data)
    

    运行结果:

    该方法不能直接对列表进行 json 序列化

    需要加个 safe=False

    from django.shortcuts import render, HttpResponse
    
    # json 测试
    def json_test(request):
        data = {"name": "Jack", "age": 18}
        hobby = ["Music", "Movie", "Basketball", "Reading"]
        
        from django.http import HttpResponse, JsonResponse
        return JsonResponse(hobby, safe=False)
    

    运行结果:

  • 相关阅读:
    飞机大战4-我的子弹
    飞机大战3-我的飞机
    飞机大战1-分析设计
    继承
    常见题
    42个例子算法
    心跳
    tomcat
    service
    URI URL
  • 原文地址:https://www.cnblogs.com/sch01ar/p/11272546.html
Copyright © 2011-2022 走看看