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?
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
.