Skip to content Skip to sidebar Skip to footer

Downloading Json Including Newline Characters Via Data Uri

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() {

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

Post a Comment for "Downloading Json Including Newline Characters Via Data Uri"