jQuery将json字符串显示在页面上

js代码:

 1 function syntaxHighlight(json) {
 2     if (typeof json != 'string') {
 3         json = JSON.stringify(json, undefined, 2);
 4     }
 5     json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
 6     return json.replace(/("(\u[a-zA-Z0-9]{4}|\[^u]|[^\"])*"(s*:)?|(true|false|null)|-?d+(?:.d*)?(?:[eE][+-]?d+)?)/g, function(match) {
 7         var cls = 'number';
 8         if (/^"/.test(match)) {
 9             if (/:$/.test(match)) {
10                 cls = 'key';
11             } else {
12                 cls = 'string';
13             }
14         } else if (/true|false/.test(match)) {
15             cls = 'boolean';
16         } else if (/null/.test(match)) {
17             cls = 'null';
18         }
19         return '<span class="' + cls + '">' + match +'</span>';
20     });
21 }

css:

1 <style type="text/css">
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>

html:

 1 <pre id="response_json"></pre> 

原文地址:https://www.cnblogs.com/myprovencesky/p/8317008.html