通过数据 uri 下载包含换行符的 json



我有一个Web应用程序,其中我生成了一个巨大的JSON。我现在希望用户能够下载该 JSON。因此,我使用以下代码:

function saveJSON() {
        var data = JSON.parse(localStorage.getItem('result'));
        var jsonResult = [];
        for (i = 0; i < data.length; i++) {
            var item = expandJsonInJson(data[i]);
            lineToWrite = JSON.stringify(item, undefined, "t").replace(/n/g, "rn");
            jsonResult.push(lineToWrite);
        }
        if (jsonResult.length != 0) {
            console.debug(jsonResult);
            saveText(jsonResult, 'logentries.txt');
        } else {
            $('#coapEntries')
                .append('<li class="visentry">' + "Your query returned no data!" +
                    '</li>');
        }
    }
function saveText(text, filename) {
    var a = document.createElement('a');
    a.setAttribute('href', 'data:application/octet-stream;charset=utf-8,' + text);
    a.setAttribute('download', filename);
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}

但是,生成的文件不包含任何换行符,它是一行。我在调用 saveText 之前打印的控制台上的输出仍然包含换行符。谁能告诉我为什么会发生这种情况以及如何防止在保存文件时删除换行符?

问题在于不同操作系统上的不同行尾。 试试这个例子...

var json = '{nt"foo": 23,nt"bar": "hello"n}';
var a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('href', 'data:application/json;charset=utf-8,' + encodeURIComponent(json));
a.setAttribute('download', 'test.json');
a.click();
var jsonWindows = '{rnt"foo": 23,rnt"bar": "hello"rn}';
a.setAttribute('href', 'data:application/json;charset=utf-8,' + encodeURIComponent(jsonWindows));
a.setAttribute('download', 'test (Windows).json');
a.click();

您最终可以检测主机操作系统并将所有n替换为 rn

最新更新