在Django中,可以使用HttpResponse对象将JSON数据作为附件下载。以下是实现下载JSON文件接口的示例代码:

import json
from django.http import HttpResponse

def download_json(request):
    data = {'key1': 'value1', 'key2': 'value2'}
    json_data = json.dumps(data)
    response = HttpResponse(json_data, content_type='application/json')
    response['Content-Disposition'] = 'attachment; filename="data.json"'
    return response

在上面的代码中,我们首先创建一个字典对象,将其转换为JSON格式并将其存储在变量json_data中。然后,我们使用HttpResponse对象将JSON数据作为附件下载。我们设置response的content_type为'application/json',这将告诉浏览器返回的内容是JSON格式的数据。我们还设置response的Content-Disposition头部,以指定文件名为"data.json"并将其作为附件下载。

在视图函数中调用download_json函数即可下载JSON文件:

def my_view(request):
    # ...
    return download_json(request)
``
django实现下载json文件接口 而不是浏览器打开json文件 是下载文件

原文地址: https://www.cveoy.top/t/topic/fJLm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录