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

运行结果:

Python - Django - JsonResponse 对象

 

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)

运行结果:

Python - Django - JsonResponse 对象

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

Python - Django - JsonResponse 对象

需要加个 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)

运行结果:

Python - Django - JsonResponse 对象