将 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
|
< html > < head > < meta charset = "utf-8" /> < title >hello</ title > < style > pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; } .string { color: green; } .number { color: darkorange; } .boolean { color: blue; } .null { color: magenta; } .key { color: red; } </ style > < script type = "text/javascript" > function syntaxHighlight(json) { if (typeof json != 'string') { json = JSON.stringify(json, undefined, 2); } json = json.replace(/&/g, '&').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 + '</ span >'; }); } </ script > </ head > < body > < pre id = "result" > </ pre > < script type = "text/javascript" > var songResJson={ "service": "ALL", "qt": 581, "content": { "answer": { "song": "如果缘只到遇见", "album": "如果缘只到遇见", "artist": "吴奇隆 严艺丹", "pic_url": "http://p1.music.126.net/-u3WgIXsFNCW7d8Jy7pCEA==/5921969627395387.jpg" }, "scene": "music" } } document.getElementById('result').innerHTML = syntaxHighlight(songResJson); // $('#result').html(syntaxHighlight(songResJson)); </ script > </ body > </ html > |