【JS】jquery展示JSON插件JSONView
JSONView介绍
jQuery插件,用于显示漂亮的JSON。
官网地址:https://plugins.jquery.com/jsonview/
git地址:https://github.com/yesmeck/jquery-jsonview
JSONView使用
1、下载jsonview插件
2、在html中引入插件
<link rel="stylesheet" href="jquery.jsonview.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="jquery.jsonview.js"></script>
3、js中调用(本例对js做了修改,多引入了2个选项:key_marks、link_marks)
<script type="text/javascript">
var json = {
"he<y": "guy",
"anumber": 243,
"anobject": {
"whoa": "nuts",
"anarray": [1, 2, "thr<h1>ee"],
"more":"stuff"
},
"awesome": true,
"bogus": false,
"meaning": null,
"japanese":"明日がある。",
"link": "http://jsonview.com",
"notLink": "http://jsonview.com is great",
"multiline": ['Much like me, you make your way forward,',
'Walking with downturned eyes.',
'Well, I too kept mine lowered.',
'Passer-by, stop here, please.'].join("\n")
};
$(function() {
$("#json").JSONView(json); /*
collapsed:是否在第一次渲染时收缩所有的节点,默认值为:false。
nl2br:是否将一个新行转换为<br>字符串,默认值为false。
recursive_collapser:是否递归收缩节点,默认值为false。
key_marks:是否为key添加双引号,默认值为false。
link_marks:是否为连接添加双引号,默认值为false。
*/
$("#json-collapsed").JSONView(json, { collapsed: true, nl2br: true, recursive_collapser: true, key_marks: true, link_marks: true }); $('#collapse-btn').on('click', function() {
$('#json').JSONView('collapse');
}); $('#expand-btn').on('click', function() {
$('#json').JSONView('expand');
}); $('#toggle-btn').on('click', function() {
$('#json').JSONView('toggle');
}); $('#toggle-level1-btn').on('click', function() {
$('#json').JSONView('toggle', 1);
}); $('#toggle-level2-btn').on('click', function() {
$('#json').JSONView('toggle', 2);
});
});
</script>
具体html,js,css文件如下:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JQuery JSONView</title>
<link rel="stylesheet" href="jquery.jsonview.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="jquery.jsonview.js"></script>
<script type="text/javascript">
var json = {
"he<y": "guy",
"anumber": 243,
"anobject": {
"whoa": "nuts",
"anarray": [1, 2, "thr<h1>ee"],
"more":"stuff"
},
"awesome": true,
"bogus": false,
"meaning": null,
"japanese":"明日がある。",
"link": "http://jsonview.com",
"notLink": "http://jsonview.com is great",
"multiline": ['Much like me, you make your way forward,',
'Walking with downturned eyes.',
'Well, I too kept mine lowered.',
'Passer-by, stop here, please.'].join("\n")
};
$(function() {
$("#json").JSONView(json); /*
collapsed:是否在第一次渲染时收缩所有的节点,默认值为:false。
nl2br:是否将一个新行转换为<br>字符串,默认值为false。
recursive_collapser:是否递归收缩节点,默认值为false。
key_marks:是否为key添加双引号,默认值为false。
link_marks:是否为连接添加双引号,默认值为false。
*/
$("#json-collapsed").JSONView(json, { collapsed: true, nl2br: true, recursive_collapser: true, key_marks: true, link_marks: true }); $('#collapse-btn').on('click', function() {
$('#json').JSONView('collapse');
}); $('#expand-btn').on('click', function() {
$('#json').JSONView('expand');
}); $('#toggle-btn').on('click', function() {
$('#json').JSONView('toggle');
}); $('#toggle-level1-btn').on('click', function() {
$('#json').JSONView('toggle', 1);
}); $('#toggle-level2-btn').on('click', function() {
$('#json').JSONView('toggle', 2);
});
});
</script>
</head>
<body>
<h2>Data</h2>
<button id="collapse-btn">Collapse</button>
<button id="expand-btn">Expand</button>
<button id="toggle-btn">Toggle</button>
<button id="toggle-level1-btn">Toggle level1</button>
<button id="toggle-level2-btn">Toggle level2</button>
<div id="json"></div>
<h2>Data Collapsed</h2>
<div id="json-collapsed"></div>
</body>
</html>
index.html
/*!
jQuery JSONView.
Licensed under the MIT License.
*/
(function(jQuery) {
var $, Collapser, JSONFormatter, JSONView, JSON_VALUE_TYPES;
JSON_VALUE_TYPES = ['object', 'array', 'number', 'string', 'boolean', 'null'];
JSONFormatter = (function() {
function JSONFormatter(options) {
if (options == null) {
options = {};
}
this.options = options;
} JSONFormatter.prototype.htmlEncode = function(html) {
if (html !== null) {
return html.toString().replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
} else {
return '';
}
}; JSONFormatter.prototype.jsString = function(s) {
s = JSON.stringify(s).slice(1, -1);
return this.htmlEncode(s);
}; JSONFormatter.prototype.decorateWithSpan = function(value, className) {
return "<span class=\"" + className + "\">" + (this.htmlEncode(value)) + "</span>";
}; JSONFormatter.prototype.valueToHTML = function(value, level) {
var valueType;
if (level == null) {
level = 0;
}
valueType = Object.prototype.toString.call(value).match(/\s(.+)]/)[1].toLowerCase();
if (this.options.strict && !jQuery.inArray(valueType, JSON_VALUE_TYPES)) {
throw new Error("" + valueType + " is not a valid JSON value type");
}
return this["" + valueType + "ToHTML"].call(this, value, level);
}; JSONFormatter.prototype.nullToHTML = function(value) {
return this.decorateWithSpan('null', 'null');
}; JSONFormatter.prototype.undefinedToHTML = function() {
return this.decorateWithSpan('undefined', 'undefined');
}; JSONFormatter.prototype.numberToHTML = function(value) {
return this.decorateWithSpan(value, 'num');
}; JSONFormatter.prototype.stringToHTML = function(value) {
var multilineClass, newLinePattern;
if (/^(http|https|file):\/\/[^\s]+$/i.test(value)) {
if(this.options.link_marks) {
return "<a href=\"" + (this.htmlEncode(value)) + "\"><span class=\"p\">\"</span>" + (this.jsString(value)) + "<span class=\"p\">\"</span></a>";
}else {
return "<a href=\"" + (this.htmlEncode(value)) + "\"><span class=\"q\">\"</span>" + (this.jsString(value)) + "<span class=\"q\">\"</span></a>";
} } else {
multilineClass = '';
value = this.jsString(value);
if (this.options.nl2br) {
newLinePattern = /([^>\\r\\n]?)(\\r\\n|\\n\\r|\\r|\\n)/g;
if (newLinePattern.test(value)) {
multilineClass = ' multiline';
value = (value + '').replace(newLinePattern, '$1' + '<br />');
}
}
return "<span class=\"string" + multilineClass + "\">\"" + value + "\"</span>";
}
}; JSONFormatter.prototype.booleanToHTML = function(value) {
return this.decorateWithSpan(value, 'bool');
}; JSONFormatter.prototype.arrayToHTML = function(array, level) {
var collapsible, hasContents, index, numProps, output, value, _i, _len;
if (level == null) {
level = 0;
}
hasContents = false;
output = '';
numProps = array.length;
for (index = _i = 0, _len = array.length; _i < _len; index = ++_i) {
value = array[index];
hasContents = true;
output += '<li>' + this.valueToHTML(value, level + 1);
if (numProps > 1) {
output += ',';
}
output += '</li>';
numProps--;
}
if (hasContents) {
collapsible = level === 0 ? '' : ' collapsible';
return "[<ul class=\"array level" + level + collapsible + "\">" + output + "</ul>]";
} else {
return '[ ]';
}
}; JSONFormatter.prototype.objectToHTML = function(object, level) {
var collapsible, hasContents, key, numProps, output, prop, value;
if (level == null) {
level = 0;
}
hasContents = false;
output = '';
numProps = 0;
for (prop in object) {
numProps++;
}
for (prop in object) {
value = object[prop];
hasContents = true;
key = this.options.escape ? this.jsString(prop) : prop;
if(this.options.key_marks) {
output += "<li><a class=\"prop\" href=\"javascript:;\"><span class=\"p\">\"</span>" + key + "<span class=\"p\">\"</span></a>: " + (this.valueToHTML(value, level + 1));
}else {
output += "<li><a class=\"prop\" href=\"javascript:;\"><span class=\"q\">\"</span>" + key + "<span class=\"q\">\"</span></a>: " + (this.valueToHTML(value, level + 1));
} if (numProps > 1) {
output += ',';
}
output += '</li>';
numProps--;
}
if (hasContents) {
collapsible = level === 0 ? '' : ' collapsible';
return "{<ul class=\"obj level" + level + collapsible + "\">" + output + "</ul>}";
} else {
return '{ }';
}
}; JSONFormatter.prototype.jsonToHTML = function(json) {
return "<div class=\"jsonview\">" + (this.valueToHTML(json)) + "</div>";
}; return JSONFormatter; })();
(typeof module !== "undefined" && module !== null) && (module.exports = JSONFormatter);
Collapser = (function() {
function Collapser() {} Collapser.bindEvent = function(item, options) {
var collapser;
item.firstChild.addEventListener('click', (function(_this) {
return function(event) {
return _this.toggle(event.target.parentNode.firstChild, options);
};
})(this));
collapser = document.createElement('div');
collapser.className = 'collapser';
collapser.innerHTML = options.collapsed ? '+' : '-';
collapser.addEventListener('click', (function(_this) {
return function(event) {
return _this.toggle(event.target, options);
};
})(this));
item.insertBefore(collapser, item.firstChild);
if (options.collapsed) {
return this.collapse(collapser);
}
}; Collapser.expand = function(collapser) {
var ellipsis, target;
target = this.collapseTarget(collapser);
if (target.style.display === '') {
return;
}
ellipsis = target.parentNode.getElementsByClassName('ellipsis')[0];
target.parentNode.removeChild(ellipsis);
target.style.display = '';
return collapser.innerHTML = '-';
}; Collapser.collapse = function(collapser) {
var ellipsis, target;
target = this.collapseTarget(collapser);
if (target.style.display === 'none') {
return;
}
target.style.display = 'none';
ellipsis = document.createElement('span');
ellipsis.className = 'ellipsis';
ellipsis.innerHTML = ' … ';
target.parentNode.insertBefore(ellipsis, target);
return collapser.innerHTML = '+';
}; Collapser.toggle = function(collapser, options) {
var action, collapsers, target, _i, _len, _results;
if (options == null) {
options = {};
}
target = this.collapseTarget(collapser);
action = target.style.display === 'none' ? 'expand' : 'collapse';
if (options.recursive_collapser) {
collapsers = collapser.parentNode.getElementsByClassName('collapser');
_results = [];
for (_i = 0, _len = collapsers.length; _i < _len; _i++) {
collapser = collapsers[_i];
_results.push(this[action](collapser));
}
return _results;
} else {
return this[action](collapser);
}
}; Collapser.collapseTarget = function(collapser) {
var target, targets;
targets = collapser.parentNode.getElementsByClassName('collapsible');
if (!targets.length) {
return;
}
return target = targets[0];
}; return Collapser; })();
$ = jQuery;
JSONView = {
collapse: function(el) {
if (el.innerHTML === '-') {
console.log('collapse:' + el);
return Collapser.collapse(el);
}
},
expand: function(el) {
if (el.innerHTML === '+') {
console.log('expand:' + el);
return Collapser.expand(el);
}
},
toggle: function(el) {
console.log('toggle:' + el);
return Collapser.toggle(el);
}
};
return $.fn.JSONView = function() {
var args, defaultOptions, formatter, json, method, options, outputDoc;
args = arguments;
if (JSONView[args[0]] != null) {
method = args[0];
return this.each(function() {
var $this, level;
$this = $(this);
if (args[1] != null) {
level = args[1];
return $this.find(".jsonview .collapsible.level" + level).siblings('.collapser').each(function() {
return JSONView[method](this);
});
} else {
return $this.find('.jsonview > ul > li .collapsible').siblings('.collapser').each(function() {
return JSONView[method](this);
});
}
});
} else {
json = args[0];
options = args[1] || {};
defaultOptions = {
collapsed: false,
nl2br: false,
recursive_collapser: false,
escape: true,
strict: false,
key_marks: false,
link_marks: false
};
options = $.extend(defaultOptions, options);
formatter = new JSONFormatter(options);
if (Object.prototype.toString.call(json) === '[object String]') {
json = JSON.parse(json);
}
outputDoc = formatter.jsonToHTML(json);
return this.each(function() {
var $this, item, items, _i, _len, _results;
$this = $(this);
$this.html(outputDoc);
items = $this[0].getElementsByClassName('collapsible');
_results = [];
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
if (item.parentNode.nodeName === 'LI') {
_results.push(Collapser.bindEvent(item.parentNode, options));
} else {
_results.push(void 0);
}
}
return _results;
});
}
};
})(jQuery);
jquery.jsonview.js
@charset "UTF-8";
.jsonview {
font-family: monospace;
font-size: 1.1em;
white-space: pre-wrap; }
.jsonview .prop {
font-weight: bold;
text-decoration: none;
color: #000; }
.jsonview .null {
color: red; }
.jsonview .undefined {
color: red; }
.jsonview .bool {
color: blue; }
.jsonview .num {
color: blue; }
.jsonview .string {
color: green;
white-space: pre-wrap; }
.jsonview .string.multiline {
display: inline-block;
vertical-align: text-top; }
.jsonview .collapser {
position: absolute;
left: -1em;
cursor: pointer; }
.jsonview .collapsible {
transition: height 1.2s;
transition: width 1.2s; }
.jsonview .collapsible.collapsed {
height: .8em;
width: 1em;
display: inline-block;
overflow: hidden;
margin:; }
.jsonview .collapsible.collapsed:before {
content: "…";
width: 1em;
margin-left: .2em; }
.jsonview .collapser.collapsed {
transform: rotate(0deg); }
.jsonview .q {
display: inline-block;
width: 0px;
color: transparent; }
.jsonview li {
position: relative; }
.jsonview ul {
list-style: none;
margin: 0 0 0 2em;
padding:; }
.jsonview h1 {
font-size: 1.2em; } /*# sourceMappingURL=jquery.jsonview.css.map */
jquery.jsonview.css
4、展示效果如下:

【JS】jquery展示JSON插件JSONView的更多相关文章
- js,jquery转json的几种方法
一.原生js转json, eval()方法,不需要引入外部插件; //由JSON字符串转换为JSON对象 var obj = eval('(' + jsonStr + ')'); 或者 var obj ...
- 同时处理html+js+jquery+css的插件安装(Spket&Aptana插件安装)
Spket 在线安装方法:Help->Software Updates(或者Install New Software)->Add site Location:http://www.spke ...
- jquery.cookie.js——jquery的cookie插件
一.JS文件 /*! * jQuery Cookie Plugin v1.4.1 * https://github.com/carhartl/jquery-cookie * * Copyright 2 ...
- JS/Jquery遍历JSON对象、JSON数组、JSON数组字符串、JSON对象字符串
JS遍历JSON对象 JS遍历JSON对象 <script> var obj = { "goodsid": "01001", "goods ...
- js(jquery)右键菜单插件的实现
今天开发一个项目的时候需要一个模拟鼠标右键菜单的功能.也就是在网页点击鼠标右键的时候不是弹出系统的菜单而是我们制定的内容.这样可以拓展右键的功能.实现过程不多说了,写出来的代码和效果如下: js部分: ...
- JS JQuery 操作: Json转 Excel 下载文件
方法的调用 var json = '[' + '{"申请流水号":"123456","保险公司":"测试数据",&quo ...
- Vue ----------- 了解, 展示json 数据
Vue.js 是一套构建用户界面的渐进式框架. 优点: 与大型框架不同的是采用自底向上的增量开发的设计, 只聚焦于视图层,不仅易于上手,还便于与第三方库或既有项目整合 当与现代化工具链以及各种类库结 ...
- Jquery.validate.js表单验证插件的使用
作为一个网站web开发人员,以前居然不知道还有表单验证这样好呀的插件,还在一行行写表单验证,真是后悔没能早点知道他们的存在. 最近公司不忙,自己学习一些东西的时候,发现了validation的一个实例 ...
- jQuery图片切换插件jquery.cycle.js
Cycle是一个很棒的jQuery图片切换插件,提供了非常好的功能来帮助大家更简单的使用插件的幻灯功能 下载cycle插件并引入,此时,注意把引入它的代码放在引入jQuery主文件之后. <he ...
随机推荐
- EF映射——从数据库更新实体
最近在做ITOO项目,由于更新了数据库,需要重新从数据库映射到实体,本来看过关于EF的学习资料,直接可以从数据库更新到实体,但这种小事也是有很多问题的,必须在更新的时候做好选择.下面分享一下如何从数据 ...
- Django --- ajax结合sweetalert使用,分页器,bulk_create批量创建数据
目录 ajax结合sweetalert使用 bulk_create批量插入数据 分页器的使用 ajax结合sweetalert使用 ajax可以在不刷新页面的情况下与后端进行交互,在对数据进行操作的时 ...
- Zookeeper中的watcher监听和leader选举机制
watcher监听 什么是watcher接口 同一个事件类型在不同的通知状态中代表的含义有所不同,下图列举了常见的通知状态和事件类型. Watcher通知状态与事件类型一览 上图列举了ZooKeepe ...
- [php]Windows环境下Composer的安装教程
方法一: 下载Composer-Setup.exe后安装,它会自动搜索 php.exe 路径, 如果找不到,则手动添加路径. Windows安装Composer 方法二: 如果出现如下错误,说明伟 ...
- C# 坦克大战笔记(1)
1.游戏对象父类:GameObject 成员: 游戏对象的X,Y坐标,高度,宽度,方向,对象,以及生命值. 绘制游戏对象的抽象方法Draw(); 绘制对象移动的方法Move() 返回矩形的方法,用于碰 ...
- 请解释或描述一下Django的架构
对于Django框架遵循MVC设计,并且有一个专有名词:MVT M全拼为Model,与MVC中的M功能相同,负责数据处理,内嵌了ORM框架 V全拼为View,与MVC中的C功能相同,接收HttpReq ...
- C语言 memset函数及其用法
定义 void *memset(void *s, int c, unsigned long n); 描述 将指针变量 s 所指向的前 n 字节的内存单元用一个“整数” c 替换,注意 c 是 int ...
- IDEA中常用快捷键
Alt+Enter 牛掰的万能快捷键,实现接口和抽象类.导入包.异常捕获.转换lambda表达式.equals的翻转和更换访问修饰符等,无所不能. Ctrl+D 复制当前行 Ctrl+Y 删除行 ...
- vim配图
https://blog.csdn.net/zhlh_xt/article/details/52458672 https://www.jianshu.com/p/75cde8a80fd7 https: ...
- 分享7个shell脚本实例--shell脚本练习必备
概述 看多shell脚本实例自然就会有shell脚本的编写思路了,所以我一般比较推荐看脚本实例来练习shell脚本.下面分享几个shell脚本实例. 1.监测Nginx访问日志502情况,并做相应动作 ...