Downloading json including newline characters via data uri

和自甴很熟 提交于 2019-12-13 05:31:10

问题


I have a web application in which I have generated a huge JSON. I now want the user to be able to download that JSON. Therefore, I use the following code:

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, "\r\n");
            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);
}

However, the resulting file does not contain any newlines, it is a single line. The output on the console, which I print just before calling saveText still contains the newline characters. Can anyone tell me why this happens and how I can prevent the removal of newline characters when saving the file?


回答1:


Problem lies in different line endings on different OS. Try this example...

var json = '{\n\t"foo": 23,\n\t"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 = '{\r\n\t"foo": 23,\r\n\t"bar": "hello"\r\n}';

a.setAttribute('href', 'data:application/json;charset=utf-8,' + encodeURIComponent(jsonWindows));
a.setAttribute('download', 'test (Windows).json');

a.click();

You can eventually detect host OS and replace all \n with \r\n.



来源:https://stackoverflow.com/questions/49128196/downloading-json-including-newline-characters-via-data-uri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!