I have a function that is taking a javascript object and attempting to download it into a .json file, but it’s being printed as flat text. Is there any way I can get this to be .json formatted in the file? Also would prefer not to have to install any third-party libraries if possible.
downloadJSON(jsonFile: any, fileName: string){
let sJson = JSON.stringify(jsonFile);
let file = new Blob([sJson], {type: 'application/json'})
let element = document.createElement('a');
let url = URL.createObjectURL(file);
element.setAttribute('href', url);
element.setAttribute('download', fileName);
element.style.display = 'none';
document.body.appendChild(element);
element.click(); // simulate click
document.body.removeChild(element);
}
2
Answers
It never fails that once I post on here, I immediately find the answer elsewhere after having search for hours. It's in this article: https://www.geeksforgeeks.org/how-to-pretty-print-json-string-in-javascript/
Use JSON.stringify(obj, replacer, space) method to convert JavaScript objects into strings in a pretty format.
If you want to get .json formatted file, you must set the file name with the suffix ‘.json’.