使用 JavaScript 美观印刷 JSON# x- w! {( Z& k: D9 B# Z
1 V! ]8 F. \1 ~& y8 b* U3 O% B 解决方案: - ]4 I' t3 v4 U. j. l Pretty-printing 在JSON.stringify(). 第三个参数启用漂亮的打印并设置要使用的间距:; k* T1 ] T D3 x1 X/ z$ b
var str = JSON.stringify(obj,null,二、 / spacing level = 2+ T- D; ` i7 [) }6 b
若需语法高亮,可使用一些正则表达式魔法,如下所示:' t; d* A: t5 g
# j9 h( y2 C" B& `/ a
function syntaxHighlight(json) if (typeof json != 'string') json = JSON.stringify(json,undefined,2); json = json.replace(/&/g,'&').replace(//g,'> return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\"])*"(\s*?|\b(true|false|null)\b|-?\d (?:\.\d*)?(?:[eE][ \-]?\d )?)/g,function (match) var cls = 'number if (/^"/.test(match)) if (//.test(match)) cls = 'key } else cls = 'string } } else if (/true|false/.test(match)) cls = 'boolean } else if (/null/.test(match)) cls = 'null } return '' match ' }code]查看这里的实际操作:jsfiddle, Q) v! G$ h7 B! }- U# e2 J