Skip to content
Advertisement

Download Object As Formatted JSON File

I followed this guide to download a JSON object from the browser. This is what my code looks like:

var json = this.getEditorJSON();

var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(json));
var a = document.createElement('a');
a.href = 'data:' + data;
a.download = 'resume.json';
a.innerHTML = 'download JSON';

var container = document.getElementById('container');
container.appendChild(a);
a.click();

a.remove();

But this gives me a single line file that is hard to read. Is there an easy way to format it as a readable JSON file, with newlines and indentation?

Advertisement

Answer

The JSON.stringify has three parameters, you can use third parameter for that

JSON.stringify(json, null, 4);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement