我已经开发了一个有用的工具插件,该工具插件可以接收JSON对象并呈现数据以在树层次结构中显示。 非常适合在大型JSON对象中查找节点的路径。
特征
- 通过上载JSON文件或复制并粘贴来输入JSON。
- 可扩展树视图。
- 悬停节点以查看变量的路径。
- 单击以复制节点的完整路径。
- 为复制节点路径指定自定义定界符。
示例创建JSON树调用
如果要创建自己的树,则可以使用它们来创建它们。 JSONTREEVIEWER是主要的名称空间。
$(function () {
//Initialise JQUERY4U JSON Tree Viewer
JSONTREEVIEWER.init();
//Events to load example files
$('#example1').bind('click', function () {
JSONTREEVIEWER.processJSONTree('one-level.json');
});
});
处理JSON树的主要功能
此函数确定从何处获取JSON:1)文件上传; 或2)复制并粘贴; 3)示例文件。
/*Load the JSON file either by upload or example file and process tree*/
processJSONTree: function (filename) {
$('#loading').show();
var data = '',
branches = '';
if (filename === 'copyandpastejson') {
var copypastejson = $('#copyandpastejson').val(); /*validate JSON*/
if (JSONTREEVIEWER.isValidJSON(copypastejson)) {
data = copypastejson;
} else {
return false;
}
if (data === false) {
return false;
} /*Build JSON Tree*/
JSONTREEVIEWER.buildTree(JSONTREEVIEWER.processNodes(jQuery.parseJSON(data)), filename);
} else {
//get the JSON file from file upload
$.ajax({
type: 'GET',
url: filename,
async: false,
beforeSend: function (x) {
if (x && x.overrideMimeType) {
x.overrideMimeType('application/j-son;charset=UTF-8');
}
},
dataType: 'json',
success: function (data) { /*Build JSON Tree*/
JSONTREEVIEWER.buildTree(JSONTREEVIEWER.processNodes(data), filename);
},
error: function (e) { /*Invalid JSON*/
alert('Invalid JSON: ' + e.responseText);
JSONTREEVIEWER.showErrorMsg();
return false;
}
});
}
},
建立树功能
此功能从分支构造树并将其显示在页面上。
/*Build JSON Tree*/
buildTree: function (branches, filename) {
//console.log('branches' + branches);
if (typeof branches !== 'undefined' || branches !== '') {
$('#browser').empty().html(branches);
$('#browser').treeview({
control: '#treecontrol',
add: branches
});
$('#selected_filename').html('(' + filename + ')');
$('#loading').hide();
$('#browser-text').hide();
} else {
$('#selected_filename').html('Please select JSON file above...');
$('#loading').hide();
}
},
JSON分支递归函数
此功能相当复杂,需要花费一些时间进行编码。 它基本上以递归方式获取每个JSON对象,确定类型并为分支创建HTML。
/*Process each node by its type (branch or leaf)*/
processNodes: function (node) {
var return_str = '';
switch (jQuery.type(node)) {
case 'string':
if ($('#hierarchy_chk').is(':checked')) {
return_str += '
- ' + node + '
- ' + node + '
- ' + item + ' '; return_str += JSONTREEVIEWER.processNodes(this); return_str += '
检查JSON是否有效
Helper函数检查它们的JSON是否有效,并在无效时显示一条消息。
/*Helper function to check if JSON is valid*/
isValidJSON: function (jsonData) {
try {
jsonData = jQuery.parseJSON(jsonData);
//console.log('valid json');
return true;
} catch (e) {
//console.log('invalid json');
alert(e);
JSONTREEVIEWER.showErrorMsg();
return false;
}
},
获取节点路径
此函数递归搜索HTML以构造节点的分支路径。
/*jQuery function to create path function used to get the path of the node in the tree*/
jQuery.fn.extend({
getPath: function (path) { /*The first time this function is called, path won't be defined*/
if (typeof path == 'undefined') path = ''; /*Add the element name*/
var cur = this.get(0).nodeName.toLowerCase();
var id = this.attr('id'); /*Add the #id if there is one*/
if (typeof id != 'undefined') { /*escape goat*/
if (id == 'browser') {
return path;
}
}
var html = this.html();
if (html.search('
- ' + path); } else { return this.parent().getPath(path); } } });
大事记
当用户上传JSON文件或将鼠标悬停在树上时,一些用于处理事件的函数。
/*change event when user changes file upload input*/ $('#loadfile').live('change', function () { JSONTREEVIEWER.processJSONTree($(this).val()); }); /*store nodepath value to clipboard (copy to top of page)*/ $('#browser li').live('click', function () { var path = $('#pathtonode').html(); var pathdelim = $('#pathdelim_chk').val(); path = path.replace(/ > /g, pathdelim); JSONTREEVIEWER.addtoppath(path); }); /*mouse IN hover to show path of node*/ $('#browser li span').live('mouseenter', function () { $('#pathtonode').html(JSONTREEVIEWER.getNodePath(this)); $('#pathtonode').show(); }); /*mouse OUT hover to show path of node*/ $('#browser li span').live('mouseleave', function () { $('#pathtonode').empty(); $('#pathtonode').hide(); });
要求
我使用了jquery.treeview.async.js插件来创建可扩展树视图。