方式一:以默認黑體顯示Json字符串。
我們經常會遇到想調試看下返回的Json字符串正不正確,以前總是使用 alert(JsonUti.convertToString(data));
但是JsonUti方法要引用一個JsonToString.js文件,這樣就導致我每個項目中都要在Script文件夾中放一個JsonToString.js文件,然后在Shared里面的模板中引用。
但其實這種返回的結果和 JSON本身的JSON.stringify顯示方式是一樣的。可以直接不必要那么麻煩去引用JsonToString.js文件,而直接通過JSON.stringify(res, null, 2) 這種方式調用即可。
其中res是要JSON化的對象,2是spacing 。
以上方式為方式一,顯示時,所有字符以默認黑體顯示,如果要想顯示的更直觀,清晰一點,建議采用以下方式二顯示。
方式二:以彩色字體顯示Json字符串
1.創建樣式文件:
@*Json樣式*@

1 <style> 2 pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; } 3 .string { color: green; } 4 .number { color: darkorange; } 5 .boolean { color: blue; } 6 .null { color: magenta; } 7 .key { color: red; } 8 </style> 9 10
2.格式化Json方法

1 <script type="text/javascript"> 2 3 function syntaxHighlight(json) { 4 if (typeof json != 'string') { 5 json = JSON.stringify(json, undefined, 2); 6 } 7 json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); 8 return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) { 9 var cls = 'number'; 10 if (/^"/.test(match)) { 11 if (/:$/.test(match)) { 12 cls = 'key'; 13 } else { 14 cls = 'string'; 15 } 16 } else if (/true|false/.test(match)) { 17 cls = 'boolean'; 18 } else if (/null/.test(match)) { 19 cls = 'null'; 20 } 21 return '<span class="' + cls + '">' + match + '</span>'; 22 }); 23 } 24 </script>
3.在html上添加一個<pre></pre>用戶顯示
<pre id="result">
</pre>
4.在方法中添加調用方法:
$('#result').html(syntaxHighlight(data));
顯示效果如下圖: