按格式下载对象 JSON 文件

Download Object As Formatted JSON File

我按照 this guide 从浏览器下载了一个 JSON 对象。这是我的代码的样子:

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

但这给了我一个难以阅读的单行文件。有没有一种简单的方法可以将其格式化为可读的 JSON 文件,并带有换行符和缩进?

JSON.stringify有三个参数,你可以用第三个参数

JSON.stringify(json, null, 4);