Guest User

jQuery Json Formatter plugin v0.1.3

a guest
Apr 24th, 2013
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  * Collapsible JSON Formatter - Formatter and colorer of raw JSON code
  3.  *
  4.  * jQuery Json Formatter plugin v0.1.3
  5.  *
  6.  * Usage
  7.  * -----
  8.  *
  9.  * $('#target').jsonFormat('#source'); // or
  10.  * $('#target').jsonFormat('#source', {options override defaults}); // see jf.config
  11.  * #target {
  12.  *     font-family: monospace;
  13.  *     white-space: pre; // or pre-wrap // All fails without this one!
  14.  * }
  15.  *
  16.  * License
  17.  * -------
  18.  *
  19.  * Copyright (c) 2008-2009 Vladimir Bodurov
  20.  * http://quickjsonformatter.codeplex.com/
  21.  *
  22.  * Copyright (c) 2012 Redsandro - Made jQuery plugin
  23.  * http://www.redsandro.com/
  24.  *
  25.  * The MIT License (MIT)
  26.  *
  27.  * Permission is hereby granted, free of charge, to any person obtaining
  28.  * a copy of this software and associated documentation files (the "Software"),
  29.  * to deal in the Software without restriction, including without limitation
  30.  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  31.  * and/or sell copies of the Software, and to permit persons to whom the
  32.  * Software is furnished to do so, subject to the following conditions:
  33.  *
  34.  * The above copyright notice and this permission notice shall be included
  35.  * in all copies or substantial portions of the Software.
  36.  */
  37.  
  38.  
  39.  
  40. jQuery.fn.jsonFormat = function(src, params) {
  41.     var jf = {
  42.         config : {
  43.             TAB : '    ',
  44.             depth: false,
  45.             ImgCollapsed : "img/Collapsed.gif",
  46.             ImgExpanded : "img/Expanded.gif",
  47.             QuoteKeys : true,
  48.             IsCollapsible : true,
  49.             _dateObj : new Date(),
  50.             _regexpObj : new RegExp()          
  51.         },
  52.        
  53.         /**
  54.          * Process - starts processing the JSON
  55.          * @param json - input JSON string
  56.          * @returns {String} html formatted JSON
  57.          */
  58.         Process : function(json) {
  59.             var html = "";
  60.             try {
  61.                 if (json == "")
  62.                     json = "\"\"";
  63.                 var obj = eval("[" + json + "]");
  64.                 html = jf.ProcessObject(obj[0], 0, false, false, false);
  65.                 return html;
  66.             } catch (e) {
  67.                 return "JSON invalid.\n" + e.message;
  68.             }
  69.         },
  70.         ProcessObject : function(obj, indent, addComma, isArray, isPropertyContent) {
  71.             var html = "";
  72.             var comma = (addComma) ? "<span class='Comma'>,</span> " : "";
  73.             var type = typeof obj;
  74.             var clpsHtml = "";
  75.             if (jf.IsArray(obj)) {
  76.                 if (obj.length == 0) {
  77.                     html += jf.GetRow(indent, "<span class='ArrayBrace'>[ ]</span>"
  78.                             + comma, isPropertyContent);
  79.                 } else {
  80.                     clpsHtml = jf.config.IsCollapsible ? "<span><img src=\""
  81.                             + jf.config.ImgExpanded
  82.                             + "\" onClick=\"jQuery().jsonFormat(this)\" /></span><span class='collapsible'>"
  83.                             : "";
  84.                     html += jf.GetRow(indent, "<span class='ArrayBrace'>[</span>"
  85.                             + clpsHtml, isPropertyContent);
  86.                     for ( var i = 0; i < obj.length; i++) {
  87.                         html += jf.ProcessObject(obj[i], indent + 1, i < (obj.length - 1),
  88.                                 true, false);
  89.                     }
  90.                     clpsHtml = jf.config.IsCollapsible ? "</span>" : "";
  91.                     html += jf.GetRow(indent, clpsHtml
  92.                             + "<span class='ArrayBrace'>]</span>" + comma);
  93.                 }
  94.             } else if (type == 'object') {
  95.                 if (obj == null) {
  96.                     html += jf.FormatLiteral("null", "", comma, indent, isArray, "Null");
  97.                 } else if (obj.constructor == jf.config._dateObj.constructor) {
  98.                     html += jf.FormatLiteral("new Date(" + obj.getTime() + ") /*"
  99.                             + obj.toLocaleString() + "*/", "", comma, indent, isArray,
  100.                             "Date");
  101.                 } else if (obj.constructor == jf.config._regexpObj.constructor) {
  102.                     html += jf.FormatLiteral("new RegExp(" + obj + ")", "", comma, indent,
  103.                             isArray, "RegExp");
  104.                 } else {
  105.                     var numProps = 0;
  106.                     for ( var prop in obj)
  107.                         numProps++;
  108.                     if (numProps == 0) {
  109.                         html += jf.GetRow(indent, "<span class='ObjectBrace'>{ }</span>"
  110.                                 + comma, isPropertyContent);
  111.                     } else {
  112.                         clpsHtml = jf.config.IsCollapsible ? "<span><img src=\""
  113.                                 + jf.config.ImgExpanded
  114.                                 + "\" onClick=\"jQuery().jsonFormat(this)\" /></span><span class='collapsible'>"
  115.                                 : "";
  116.                         html += jf.GetRow(indent, "<span class='ObjectBrace'>{</span>"
  117.                                 + clpsHtml, isPropertyContent);
  118.                         var j = 0;
  119.                         for ( var prop in obj) {
  120.                             var quote = jf.config.QuoteKeys ? "\"" : "";
  121.                             html += jf.GetRow(indent + 1, "<span class='PropertyName'>"
  122.                                     + quote
  123.                                     + prop
  124.                                     + quote
  125.                                     + "</span>: "
  126.                                     + jf.ProcessObject(obj[prop], indent + 1,
  127.                                             ++j < numProps, false, true));
  128.                         }
  129.                         clpsHtml = jf.config.IsCollapsible ? "</span>" : "";
  130.                         html += jf.GetRow(indent, clpsHtml
  131.                                 + "<span class='ObjectBrace'>}</span>" + comma);
  132.                     }
  133.                 }
  134.             } else if (type == 'number') {
  135.                 html += jf.FormatLiteral(obj, "", comma, indent, isArray, "Number");
  136.             } else if (type == 'boolean') {
  137.                 html += jf.FormatLiteral(obj, "", comma, indent, isArray, "Boolean");
  138.             } else if (type == 'function') {
  139.                 if (obj.constructor == jf.config._regexpObj.constructor) {
  140.                     html += jf.FormatLiteral("new RegExp(" + obj + ")", "", comma, indent,
  141.                             isArray, "RegExp");
  142.                 } else {
  143.                     obj = jf.FormatFunction(indent, obj);
  144.                     html += jf.FormatLiteral(obj, "", comma, indent, isArray, "Function");
  145.                 }
  146.             } else if (type == 'undefined') {
  147.                 html += jf.FormatLiteral("undefined", "", comma, indent, isArray, "Null");
  148.             } else {
  149.                 html += jf.FormatLiteral(obj.toString().split("\\").join("\\\\")
  150.                         .split('"').join('\\"'), "\"", comma, indent, isArray, "String");
  151.             }
  152.             return html;
  153.         },
  154.         IsArray : function(obj) {
  155.             return obj && typeof obj === 'object' && typeof obj.length === 'number'
  156.                     && !(obj.propertyIsEnumerable('length'));
  157.         },
  158.         FormatLiteral : function(literal, quote, comma, indent, isArray, style) {
  159.             if (typeof literal == 'string')
  160.                 literal = literal.split("<").join("&lt;").split(">").join("&gt;");
  161.             var str = "<span class='" + style + "'>" + quote + literal + quote + comma
  162.                     + "</span>";
  163.             if (isArray)
  164.                 str = jf.GetRow(indent, str);
  165.             return str;
  166.         },
  167.         FormatFunction : function (indent, obj) {
  168.             var tabs = "";
  169.             for ( var i = 0; i < indent; i++)
  170.                 tabs += jf.config.TAB;
  171.             var funcStrArray = obj.toString().split("\n");
  172.             var str = "";
  173.             for ( var i = 0; i < funcStrArray.length; i++) {
  174.                 str += ((i == 0) ? "" : tabs) + funcStrArray[i] + "\n";
  175.             }
  176.             return str;
  177.         },
  178.         GetRow : function (indent, data, isPropertyContent) {
  179.             var tabs = "";
  180.             for ( var i = 0; i < indent && !isPropertyContent; i++)
  181.                 tabs += jf.config.TAB;
  182.             if (data != null && data.length > 0 && data.charAt(data.length - 1) != "\n")
  183.                 data = data + "\n";
  184.             return tabs + data;
  185.         },
  186.         ExpImgClicked : function (img) {
  187.             var container = img.parentNode.nextSibling;
  188.             if (!container)
  189.                 return;
  190.             var disp = "none";
  191.             var src = jf.config.ImgCollapsed;
  192.             if (container.style.display == "none") {
  193.                 disp = "inline";
  194.                 src = jf.config.ImgExpanded;
  195.             }
  196.             container.style.display = disp;
  197.             img.src = src;
  198.         }
  199.     };
  200.  
  201.     // Expand clicked?
  202.     if (src.parentNode &&
  203.         src.parentNode.nextSibling &&
  204.         src.parentNode.nextSibling.classList &&
  205.         src.parentNode.nextSibling.classList.contains('collapsible'))
  206.         jf.ExpImgClicked(src);
  207.    
  208.     // Optional settings to override jf.config
  209.     jQuery.extend(jf.config, params);
  210.    
  211.     // each, in case for some freak reason multiple target elements are selected
  212.     this.each(function() {
  213.         src = jQuery(src);
  214.         src = (src.val()) ? src.val() : src.text();
  215.         jQuery(this).html(jf.Process(src));
  216.     });
  217.    
  218.     // Daisychaining hippy love
  219.     return this;
  220. };
Advertisement
Add Comment
Please, Sign In to add comment