我看过一些问题,比如: How can I pretty-print JSON using JavaScript? 和 Javascript: How to generate formatted easy-to-read JSON straight from an object? 和 http://jsfiddle.net/AndyE/HZPVL/
但我无法让它为我工作。我一定做错了什么?有人可以建议吗?
我尝试将'\ t'添加到stringify部分,但它对我不起作用
$(document).on("click", "#doBackupBtn", function(e) {
e.preventDefault();
console.log("Begin backup process");
$.when(
backup("allergies")
).then(function(allergies, log) {
console.log("All done");
//Convert to JSON
var data = {allergies:allergies}
var serializedData = JSON.stringify(data, '\t');
console.log(serializedData);
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
答案 0 :(得分:1)
\t
是第三个参数。在浏览器控制台上尝试此操作(FF Ctrl + Shift + K):
console.log(JSON.stringify({"a": {"b": "c"}}, null, 4));
结果:
"{
"a": {
"b": "c"
}
}"
答案 1 :(得分:0)
您缺少JSON.stringify(obj, undefined,2)