我如何以易于阅读(供人类阅读)的格式显示JSON?我主要寻找缩进和空白,甚至是颜色/字体样式等。
当前回答
这是user123444555621的很棒的HTML,适合终端。易于调试节点脚本:
function prettyJ(json) {
if (typeof json !== 'string') {
json = JSON.stringify(json, undefined, 2);
}
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
function (match) {
let cls = "\x1b[36m";
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = "\x1b[34m";
} else {
cls = "\x1b[32m";
}
} else if (/true|false/.test(match)) {
cls = "\x1b[35m";
} else if (/null/.test(match)) {
cls = "\x1b[31m";
}
return cls + match + "\x1b[0m";
}
);
}
用法:
// thing = any json OR string of json
prettyJ(thing);
其他回答
用户Pumbaa80的答案很好,如果你有一个想要漂亮打印的对象。如果要从一个有效的JSON字符串开始打印,需要首先将其转换为一个对象:
var jsonString = '{"some":"json"}';
var jsonPretty = JSON.stringify(JSON.parse(jsonString),null,2);
这将从字符串构建一个JSON对象,然后使用JSON字符串的漂亮打印将其转换回字符串。
出于调试目的,我使用:
console.debug("%o", data);
https://getfirebug.com/wiki/index.php/Console_APIhttps://developer.mozilla.org/en-US/docs/DOM/console
1行代码(无颜色)中的快速易读JSON输出:
document.documentElement.innerHTML='<pre>'+JSON.stringify(obj, null, 2)+'</pre>';
为调试目的显示对象的最简单方法:
console.log("data",data) // lets you unfold the object manually
如果要在DOM中显示对象,应该考虑它可能包含将被解释为HTML的字符串。因此,你需要做一些逃避。。。
var s = JSON.stringify(data,null,2) // format
var e = new Option(s).innerHTML // escape
document.body.insertAdjacentHTML('beforeend','<pre>'+e+'</pre>') // display
我想你在找这样的东西:
JSON.stringify(obj, null, '\t');
这“漂亮地打印”了JSON字符串,使用制表符进行缩进。
如果您喜欢使用空格而不是制表符,也可以使用数字表示您想要的空格数:
JSON.stringify(obj, null, 2);