/** * jQuery json-viewer * @author: Alexandre Bodelot */ (function($){ /** * Check if arg is either an array with at least 1 element, or a dict with at least 1 key * @return boolean */ function isCollapsable(arg) { return arg instanceof Object && Object.keys(arg).length > 0; } /** * Check if a string represents a valid url * @return boolean */ function isUrl(string) { var regexp = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/; return regexp.test(string); } /** * Transform a json object into html representation * @return string */ function json2html(json, options) { var html = ''; if (typeof json === 'string') { /* Escape tags */ json = json.replace(/&/g, '&').replace(//g, '>'); if (isUrl(json)) html += '' + json + ''; else html += '"' + json + '"'; } else if (typeof json === 'number') { html += '' + json + ''; } else if (typeof json === 'boolean') { html += '' + json + ''; } else if (json === null) { html += 'null'; } else if (json instanceof Array) { if (json.length > 0) { html += '[
    '; for (var i = 0; i < json.length; ++i) { html += '
  1. '; /* Add toggle button if item is collapsable */ if (isCollapsable(json[i])) { html += ''; } html += json2html(json[i], options); /* Add comma if item is not last */ if (i < json.length - 1) { html += ','; } html += '
  2. '; } html += '
]'; } else { html += '[]'; } } else if (typeof json === 'object') { var key_count = Object.keys(json).length; if (key_count > 0) { html += '{}'; } else { html += '{}'; } } return html; } /** * jQuery plugin method * @param json: a javascript object * @param options: an optional options hash */ $.fn.jsonViewer = function(json, options) { options = options || {}; /* jQuery chaining */ return this.each(function() { /* Transform to HTML */ var html = json2html(json, options); if (isCollapsable(json)) html = '' + html; /* Insert HTML in target DOM element */ $(this).html(html); /* Bind click on toggle buttons */ $(this).off('click'); $(this).on('click', 'a.json-toggle', function() { var target = $(this).toggleClass('collapsed').siblings('ul.json-dict, ol.json-array'); target.toggle(); if (target.is(':visible')) { target.siblings('.json-placeholder').remove(); } else { var count = target.children('li').length; var placeholder = count + (count > 1 ? ' items' : ' item'); target.after('' + placeholder + ''); } return false; }); /* Simulate click on toggle button when placeholder is clicked */ $(this).on('click', 'a.json-placeholder', function() { $(this).siblings('a.json-toggle').click(); return false; }); if (options.collapsed == true) { /* Trigger click to collapse all nodes */ $(this).find('a.json-toggle').click(); } }); }; })(jQuery);