Python - Django - JsonResponse 對象


用 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)

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM