最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Download Object As Formatted JSON File - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Feb 5, 2022 at 5:57 Tanner Stern 2353 silver badges8 bronze badges asked Apr 28, 2016 at 13:36 JaskeyLamJaskeyLam 15.8k23 gold badges127 silver badges158 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 18

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

JSON.stringify(json, null, 4);
发布评论

评论列表(0)

  1. 暂无评论