【JS】jquery展示JSON插件JSONView

JSONView介绍

  jQuery插件,用于显示漂亮的JSON。

  官网地址:https://plugins.jquery.com/jsonview/

  git地址:https://github.com/yesmeck/jquery-jsonview

JSONView使用

  1、下载jsonview插件

  2、在html中引入插件

1 <link rel="stylesheet" href="jquery.jsonview.css" />
2 <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
3 <script type="text/javascript" src="jquery.jsonview.js"></script>

  3、js中调用(本例对js做了修改,多引入了2个选项:key_marks、link_marks)

 1 <script type="text/javascript">
 2     var json = {
 3       "he&lt;y": "guy",
 4       "anumber": 243,
 5       "anobject": {
 6         "whoa": "nuts",
 7         "anarray": [1, 2, "thr<h1>ee"],
 8         "more":"stuff"
 9       },
10       "awesome": true,
11       "bogus": false,
12       "meaning": null,
13       "japanese":"明日がある。",
14       "link": "http://jsonview.com",
15       "notLink": "http://jsonview.com is great",
16       "multiline": ['Much like me, you make your way forward,',
17         'Walking with downturned eyes.',
18         'Well, I too kept mine lowered.',
19         'Passer-by, stop here, please.'].join("
")
20     };
21     $(function() {
22       $("#json").JSONView(json);
23 
24       /*
25         collapsed:是否在第一次渲染时收缩所有的节点,默认值为:false。
26         nl2br:是否将一个新行转换为<br>字符串,默认值为false。
27         recursive_collapser:是否递归收缩节点,默认值为false。
28         key_marks:是否为key添加双引号,默认值为false。
29         link_marks:是否为连接添加双引号,默认值为false。
30       */
31       $("#json-collapsed").JSONView(json, { collapsed: true, nl2br: true, recursive_collapser: true,  key_marks: true, link_marks: true });
32 
33       $('#collapse-btn').on('click', function() {
34         $('#json').JSONView('collapse');
35       });
36 
37       $('#expand-btn').on('click', function() {
38         $('#json').JSONView('expand');
39       });
40 
41       $('#toggle-btn').on('click', function() {
42         $('#json').JSONView('toggle');
43       });
44 
45       $('#toggle-level1-btn').on('click', function() {
46         $('#json').JSONView('toggle', 1);
47       });
48 
49       $('#toggle-level2-btn').on('click', function() {
50         $('#json').JSONView('toggle', 2);
51       });
52     });
53   </script>

  具体html,js,css文件如下:

 1 <!DOCTYPE HTML>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <title>JQuery JSONView</title>
 6   <link rel="stylesheet" href="jquery.jsonview.css" />
 7   <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
 8   <script type="text/javascript" src="jquery.jsonview.js"></script>
 9   <script type="text/javascript">
10     var json = {
11       "he&lt;y": "guy",
12       "anumber": 243,
13       "anobject": {
14         "whoa": "nuts",
15         "anarray": [1, 2, "thr<h1>ee"],
16         "more":"stuff"
17       },
18       "awesome": true,
19       "bogus": false,
20       "meaning": null,
21       "japanese":"明日がある。",
22       "link": "http://jsonview.com",
23       "notLink": "http://jsonview.com is great",
24       "multiline": ['Much like me, you make your way forward,',
25         'Walking with downturned eyes.',
26         'Well, I too kept mine lowered.',
27         'Passer-by, stop here, please.'].join("
")
28     };
29     $(function() {
30       $("#json").JSONView(json);
31 
32       /*
33         collapsed:是否在第一次渲染时收缩所有的节点,默认值为:false。
34         nl2br:是否将一个新行转换为<br>字符串,默认值为false。
35         recursive_collapser:是否递归收缩节点,默认值为false。
36         key_marks:是否为key添加双引号,默认值为false。
37         link_marks:是否为连接添加双引号,默认值为false。
38       */
39       $("#json-collapsed").JSONView(json, { collapsed: true, nl2br: true, recursive_collapser: true,  key_marks: true, link_marks: true });
40 
41       $('#collapse-btn').on('click', function() {
42         $('#json').JSONView('collapse');
43       });
44 
45       $('#expand-btn').on('click', function() {
46         $('#json').JSONView('expand');
47       });
48 
49       $('#toggle-btn').on('click', function() {
50         $('#json').JSONView('toggle');
51       });
52 
53       $('#toggle-level1-btn').on('click', function() {
54         $('#json').JSONView('toggle', 1);
55       });
56 
57       $('#toggle-level2-btn').on('click', function() {
58         $('#json').JSONView('toggle', 2);
59       });
60     });
61   </script>
62 </head>
63 <body>
64   <h2>Data</h2>
65   <button id="collapse-btn">Collapse</button>
66   <button id="expand-btn">Expand</button>
67   <button id="toggle-btn">Toggle</button>
68   <button id="toggle-level1-btn">Toggle level1</button>
69   <button id="toggle-level2-btn">Toggle level2</button>
70   <div id="json"></div>
71   <h2>Data Collapsed</h2>
72   <div id="json-collapsed"></div>
73 </body>
74 </html>

index.html

  1 /*!
  2 jQuery JSONView.
  3 Licensed under the MIT License.
  4  */
  5 (function(jQuery) {
  6   var $, Collapser, JSONFormatter, JSONView, JSON_VALUE_TYPES;
  7   JSON_VALUE_TYPES = ['object', 'array', 'number', 'string', 'boolean', 'null'];
  8   JSONFormatter = (function() {
  9     function JSONFormatter(options) {
 10       if (options == null) {
 11         options = {};
 12       }
 13       this.options = options;
 14     }
 15 
 16     JSONFormatter.prototype.htmlEncode = function(html) {
 17       if (html !== null) {
 18         return html.toString().replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
 19       } else {
 20         return '';
 21       }
 22     };
 23 
 24     JSONFormatter.prototype.jsString = function(s) {
 25       s = JSON.stringify(s).slice(1, -1);
 26       return this.htmlEncode(s);
 27     };
 28 
 29     JSONFormatter.prototype.decorateWithSpan = function(value, className) {
 30       return "<span class="" + className + "">" + (this.htmlEncode(value)) + "</span>";
 31     };
 32 
 33     JSONFormatter.prototype.valueToHTML = function(value, level) {
 34       var valueType;
 35       if (level == null) {
 36         level = 0;
 37       }
 38       valueType = Object.prototype.toString.call(value).match(/s(.+)]/)[1].toLowerCase();
 39       if (this.options.strict && !jQuery.inArray(valueType, JSON_VALUE_TYPES)) {
 40         throw new Error("" + valueType + " is not a valid JSON value type");
 41       }
 42       return this["" + valueType + "ToHTML"].call(this, value, level);
 43     };
 44 
 45     JSONFormatter.prototype.nullToHTML = function(value) {
 46       return this.decorateWithSpan('null', 'null');
 47     };
 48 
 49     JSONFormatter.prototype.undefinedToHTML = function() {
 50       return this.decorateWithSpan('undefined', 'undefined');
 51     };
 52 
 53     JSONFormatter.prototype.numberToHTML = function(value) {
 54       return this.decorateWithSpan(value, 'num');
 55     };
 56 
 57     JSONFormatter.prototype.stringToHTML = function(value) {
 58       var multilineClass, newLinePattern;
 59       if (/^(http|https|file)://[^s]+$/i.test(value)) {
 60         if(this.options.link_marks) {
 61           return "<a href="" + (this.htmlEncode(value)) + ""><span class="p">"</span>" + (this.jsString(value)) + "<span class="p">"</span></a>";
 62         }else {
 63           return "<a href="" + (this.htmlEncode(value)) + ""><span class="q">"</span>" + (this.jsString(value)) + "<span class="q">"</span></a>";
 64         }
 65         
 66       } else {
 67         multilineClass = '';
 68         value = this.jsString(value);
 69         if (this.options.nl2br) {
 70           newLinePattern = /([^>rn]?)(rn|nr|r|n)/g;
 71           if (newLinePattern.test(value)) {
 72             multilineClass = ' multiline';
 73             value = (value + '').replace(newLinePattern, '$1' + '<br />');
 74           }
 75         }
 76         return "<span class="string" + multilineClass + "">"" + value + ""</span>";
 77       }
 78     };
 79 
 80     JSONFormatter.prototype.booleanToHTML = function(value) {
 81       return this.decorateWithSpan(value, 'bool');
 82     };
 83 
 84     JSONFormatter.prototype.arrayToHTML = function(array, level) {
 85       var collapsible, hasContents, index, numProps, output, value, _i, _len;
 86       if (level == null) {
 87         level = 0;
 88       }
 89       hasContents = false;
 90       output = '';
 91       numProps = array.length;
 92       for (index = _i = 0, _len = array.length; _i < _len; index = ++_i) {
 93         value = array[index];
 94         hasContents = true;
 95         output += '<li>' + this.valueToHTML(value, level + 1);
 96         if (numProps > 1) {
 97           output += ',';
 98         }
 99         output += '</li>';
100         numProps--;
101       }
102       if (hasContents) {
103         collapsible = level === 0 ? '' : ' collapsible';
104         return "[<ul class="array level" + level + collapsible + "">" + output + "</ul>]";
105       } else {
106         return '[ ]';
107       }
108     };
109 
110     JSONFormatter.prototype.objectToHTML = function(object, level) {
111       var collapsible, hasContents, key, numProps, output, prop, value;
112       if (level == null) {
113         level = 0;
114       }
115       hasContents = false;
116       output = '';
117       numProps = 0;
118       for (prop in object) {
119         numProps++;
120       }
121       for (prop in object) {
122         value = object[prop];
123         hasContents = true;
124         key = this.options.escape ? this.jsString(prop) : prop;
125         if(this.options.key_marks) {
126           output += "<li><a class="prop" href="javascript:;"><span class="p">"</span>" + key + "<span class="p">"</span></a>: " + (this.valueToHTML(value, level + 1));
127         }else {
128           output += "<li><a class="prop" href="javascript:;"><span class="q">"</span>" + key + "<span class="q">"</span></a>: " + (this.valueToHTML(value, level + 1));
129         }
130         
131         if (numProps > 1) {
132           output += ',';
133         }
134         output += '</li>';
135         numProps--;
136       }
137       if (hasContents) {
138         collapsible = level === 0 ? '' : ' collapsible';
139         return "{<ul class="obj level" + level + collapsible + "">" + output + "</ul>}";
140       } else {
141         return '{ }';
142       }
143     };
144 
145     JSONFormatter.prototype.jsonToHTML = function(json) {
146       return "<div class="jsonview">" + (this.valueToHTML(json)) + "</div>";
147     };
148 
149     return JSONFormatter;
150 
151   })();
152   (typeof module !== "undefined" && module !== null) && (module.exports = JSONFormatter);
153   Collapser = (function() {
154     function Collapser() {}
155 
156     Collapser.bindEvent = function(item, options) {
157       var collapser;
158       item.firstChild.addEventListener('click', (function(_this) {
159         return function(event) {
160           return _this.toggle(event.target.parentNode.firstChild, options);
161         };
162       })(this));
163       collapser = document.createElement('div');
164       collapser.className = 'collapser';
165       collapser.innerHTML = options.collapsed ? '+' : '-';
166       collapser.addEventListener('click', (function(_this) {
167         return function(event) {
168           return _this.toggle(event.target, options);
169         };
170       })(this));
171       item.insertBefore(collapser, item.firstChild);
172       if (options.collapsed) {
173         return this.collapse(collapser);
174       }
175     };
176 
177     Collapser.expand = function(collapser) {
178       var ellipsis, target;
179       target = this.collapseTarget(collapser);
180       if (target.style.display === '') {
181         return;
182       }
183       ellipsis = target.parentNode.getElementsByClassName('ellipsis')[0];
184       target.parentNode.removeChild(ellipsis);
185       target.style.display = '';
186       return collapser.innerHTML = '-';
187     };
188 
189     Collapser.collapse = function(collapser) {
190       var ellipsis, target;
191       target = this.collapseTarget(collapser);
192       if (target.style.display === 'none') {
193         return;
194       }
195       target.style.display = 'none';
196       ellipsis = document.createElement('span');
197       ellipsis.className = 'ellipsis';
198       ellipsis.innerHTML = ' &hellip; ';
199       target.parentNode.insertBefore(ellipsis, target);
200       return collapser.innerHTML = '+';
201     };
202 
203     Collapser.toggle = function(collapser, options) {
204       var action, collapsers, target, _i, _len, _results;
205       if (options == null) {
206         options = {};
207       }
208       target = this.collapseTarget(collapser);
209       action = target.style.display === 'none' ? 'expand' : 'collapse';
210       if (options.recursive_collapser) {
211         collapsers = collapser.parentNode.getElementsByClassName('collapser');
212         _results = [];
213         for (_i = 0, _len = collapsers.length; _i < _len; _i++) {
214           collapser = collapsers[_i];
215           _results.push(this[action](collapser));
216         }
217         return _results;
218       } else {
219         return this[action](collapser);
220       }
221     };
222 
223     Collapser.collapseTarget = function(collapser) {
224       var target, targets;
225       targets = collapser.parentNode.getElementsByClassName('collapsible');
226       if (!targets.length) {
227         return;
228       }
229       return target = targets[0];
230     };
231 
232     return Collapser;
233 
234   })();
235   $ = jQuery;
236   JSONView = {
237     collapse: function(el) {
238       if (el.innerHTML === '-') {
239         console.log('collapse:' + el);
240         return Collapser.collapse(el);
241       }
242     },
243     expand: function(el) {
244       if (el.innerHTML === '+') {
245         console.log('expand:' + el);
246         return Collapser.expand(el);
247       }
248     },
249     toggle: function(el) {
250       console.log('toggle:' + el);
251       return Collapser.toggle(el);
252     }
253   };
254   return $.fn.JSONView = function() {
255     var args, defaultOptions, formatter, json, method, options, outputDoc;
256     args = arguments;
257     if (JSONView[args[0]] != null) {
258       method = args[0];
259       return this.each(function() {
260         var $this, level;
261         $this = $(this);
262         if (args[1] != null) {
263           level = args[1];
264           return $this.find(".jsonview .collapsible.level" + level).siblings('.collapser').each(function() {
265             return JSONView[method](this);
266           });
267         } else {
268           return $this.find('.jsonview > ul > li .collapsible').siblings('.collapser').each(function() {
269             return JSONView[method](this);
270           });
271         }
272       });
273     } else {
274       json = args[0];
275       options = args[1] || {};
276       defaultOptions = {
277         collapsed: false,
278         nl2br: false,
279         recursive_collapser: false,
280         escape: true,
281         strict: false,
282         key_marks: false,
283         link_marks: false
284       };
285       options = $.extend(defaultOptions, options);
286       formatter = new JSONFormatter(options);
287       if (Object.prototype.toString.call(json) === '[object String]') {
288         json = JSON.parse(json);
289       }
290       outputDoc = formatter.jsonToHTML(json);
291       return this.each(function() {
292         var $this, item, items, _i, _len, _results;
293         $this = $(this);
294         $this.html(outputDoc);
295         items = $this[0].getElementsByClassName('collapsible');
296         _results = [];
297         for (_i = 0, _len = items.length; _i < _len; _i++) {
298           item = items[_i];
299           if (item.parentNode.nodeName === 'LI') {
300             _results.push(Collapser.bindEvent(item.parentNode, options));
301           } else {
302             _results.push(void 0);
303           }
304         }
305         return _results;
306       });
307     }
308   };
309 })(jQuery);

jquery.jsonview.js

 1 @charset "UTF-8";
 2 .jsonview {
 3   font-family: monospace;
 4   font-size: 1.1em;
 5   white-space: pre-wrap; }
 6   .jsonview .prop {
 7     font-weight: bold;
 8     text-decoration: none;
 9     color: #000; }
10   .jsonview .null {
11     color: red; }
12   .jsonview .undefined {
13     color: red; }
14   .jsonview .bool {
15     color: blue; }
16   .jsonview .num {
17     color: blue; }
18   .jsonview .string {
19     color: green;
20     white-space: pre-wrap; }
21     .jsonview .string.multiline {
22       display: inline-block;
23       vertical-align: text-top; }
24   .jsonview .collapser {
25     position: absolute;
26     left: -1em;
27     cursor: pointer; }
28   .jsonview .collapsible {
29     transition: height 1.2s;
30     transition: width 1.2s; }
31   .jsonview .collapsible.collapsed {
32     height: .8em;
33     width: 1em;
34     display: inline-block;
35     overflow: hidden;
36     margin: 0; }
37   .jsonview .collapsible.collapsed:before {
38     content: "…";
39     width: 1em;
40     margin-left: .2em; }
41   .jsonview .collapser.collapsed {
42     transform: rotate(0deg); }
43   .jsonview .q {
44     display: inline-block;
45     width: 0px;
46     color: transparent; }
47   .jsonview li {
48     position: relative; }
49   .jsonview ul {
50     list-style: none;
51     margin: 0 0 0 2em;
52     padding: 0; }
53   .jsonview h1 {
54     font-size: 1.2em; }
55 
56 /*# sourceMappingURL=jquery.jsonview.css.map */

jquery.jsonview.css

  4、展示效果如下:

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注