用 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)
运行结果:
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python – Django – JsonResponse 对象 - Python技术站