html格式化输出JSON示例(测试接口)

将 json 数据以美观的缩进格式显示出来,借助最简单的 JSON.stringify 函数就可以了,因为此函数还有不常用的后面2个参数。

见MDN https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify 的描述。

示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
     
 
        <title>hello</title>
 
            pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
 
            .string { color: green; }
 
            .number { color: darkorange; }
 
            .boolean { color: blue; }
 
            .null { color: magenta; }
 
            .key { color: red; }
 
         
 
        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 '<span class="' + cls + '">' + match + '';
 
            });
 
        }
 
  
 
    <pre id="result">
  
 
    </pre>
<p>        var songResJson={  </p>
<p>              "service": "ALL",  </p>
<p>              "qt": 581,  </p>
<p>              "content": {  </p>
<p>                "answer": {  </p>
<p>                  "song": "如果缘只到遇见",  </p>
<p>                  "album": "如果缘只到遇见",  </p>
<p>                  "artist": "吴奇隆 严艺丹",  </p>
<p>                  "pic_url": "http://p1.music.126.net/-u3WgIXsFNCW7d8Jy7pCEA==/5921969627395387.jpg" </p>
<p>                },  </p>
<p>                "scene": "music" </p>
<p>              }  </p>
<p>            }</p>
<p>            document.getElementById('result').innerHTML = syntaxHighlight(songResJson);</p>
<p>        // $('#result').html(syntaxHighlight(songResJson));</p>
</span>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持IT俱乐部。

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/navsub/html/13719.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部