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)
    

    运行结果:

  • 相关阅读:
    京东精益敏捷教练分享:敏捷助力产品创新!
    设计规范 | 详解组件控件结构体系
    Axure响应式进阶
    通讯录表设计
    TEST1
    c#练习四单元总结
    窗体控件应用总结(1)
    .NET(c#理解)
    test2-11
    test1-1
  • 原文地址:https://www.cnblogs.com/sch01ar/p/11272546.html
Copyright © 2011-2022 走看看