將JSON下載爲文件

// 保存JSON文件
saveJSONFile = (data, filename) => {
    if (typeof data === 'object') {
        // data = JSON.stringify(data, null, 4)
        // 取消序列化美化
        data = JSON.stringify(data)
    }

    // 構建下載對象
    const blobURL = new Blob([data], { type: 'text/json' })
    const tempLink = document.createElement('a')
    tempLink.style.display = 'none';
    tempLink.href = window.URL.createObjectURL(blobURL)
    tempLink.download = `${filename}.json`

    // 模擬點擊
    document.body.appendChild(tempLink);
    tempLink.click();

    // 刪除DOM、釋放對象URL
    setTimeout(() => {
        document.body.removeChild(tempLink);
        window.URL.revokeObjectURL(blobURL);
    }, 200)
}
相關文章
相關標籤/搜索