Commits

James Sumners committed 71960e0

Initial commit.

Comments (0)

Files changed (3)

+# formatJSON #
+
+This [jQuery](http://jquery.com/) plugin formats a [JSON](http://json.org/) string into HTML. It includes toggling of nested arrays and objects. For a live example view [http://jsfiddle.net/jsumners/38uK4/](http://jsfiddle.net/jsumners/38uK4/).
+
+## How To Use It ##
+
+The simplest usage of the plugin merely requires an HTML element that contains a JSON string. For example:
+
+    <div id="myJSON">
+      {"foo":"bar", "items":[1,2,3,4]}
+    </div>
+
+    <script>
+      // Format the JSON in the #myJSON element.
+      $("#myJSON").formatJSON();
+    </script>
+
+You could also pass in a JSON string:
+
+    <div id="jsonOutput">
+    </div>
+
+    <script>
+      $("#jsonOutput").format({
+          jsonString: '{"foo":"bar", "items":[1,2,3,4]}'
+        });
+    </script>
+
+**Note:** the resulting HTML writes to an unordered list with an id attribute set to "formattedJSON". If you intend to have multiple instances of formatted JSON in the same document then you _must_ specify unique identifiers for each format. This is done by passing in a value for the `jsonListId` option.
+
+### Options ###
+
+Options for `formatJSON` are passed in via an object literal containing any of the following properties:
+
+* `classes`: This object specifies the class names that will be used in the resulting markup.
+  * `array`: Applied to unordered lists that represent arrays.
+  * `closeBracket`: Applied to the closing brackets `]` and `}`.
+  * `closedGroup`: Applied to unordered lists when then list items are hidden.
+  * `disclosure`: Applied to elements that are used for toggling the display of a group.
+  * `keyName`: Applied to object property names.
+  * `keyNameSeparator`: Applied to the separator between property names and values.
+  * `keyword`: Applied to the keywords `true`, `false`, and `null`.
+  * `number`: Applied to number values.
+  * `object`: Applied to unordered lists that represent objects.
+  * `openBracket`: Applied to the opening brackets `[` and `{`.
+  * `separator`: Applied the separator between items in arrays and objects.
+  * `string`: Applied to string values.
+* `collapse`: Indicates if the formatted JSON should be collapsed initially. (default: `true`)
+* `expandRoot`: Indicates if the root element of the formatted JSON should be expanded initially. (default: `true`)
+* `jsonListId`: Used as the identifier for the generated unordered list that represents the JSON string. (default: "formattedJSON")
+* `jsonString`: The JSON string that will be formatted. (default: the text of the target element)
+* `events`: An object of event callback functions.
+  * `complete`: Will be called when `formatJSON` has finished. The jQuery object representing the initial target element will be passed in as the only parameter. (default: an empty function)
+  * `disclosureClicked`: Will be called when a disclosure element is clicked. This **_will_** be called by the plugin if `collapse` or `expandRoot` are `true`.
+
+## License ##
+
+The MIT License (MIT)
+Copyright (c) <2013> <James Sumners>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

src/jquery.formatJSON.css

+#formattedJSON {
+    font-family: monospace;
+    list-style: none;
+    margin: 5px;
+}
+
+.jsonArray li,
+.jsonObject li {
+    margin-left: 2em;
+}
+
+li.jsonCloseBracket,
+li.jsonOpenBracket {
+    display: block;
+    font-weight: bold;
+    margin-left: 0em;
+}
+
+.jsonDisclosure {
+    cursor: pointer;
+}
+
+.jsonArray,
+.jsonObject {}
+
+.jsonKeyName {
+    color: green;
+    font-weight: bold;
+}
+
+.jsonKeyword {
+    color: purple;
+}
+
+.jsonNumber {
+    color: darkslateblue;
+}
+
+.jsonString {
+    color: red;
+}
+
+.jsonKeyNameSeparator,
+.jsonSeparator {
+    clear: right;
+    color: black;
+}

src/jquery.formatJSON.js

+/**
+ * The MIT License (MIT)
+ *
+ * Copyright (c) <2013> <James Sumners>
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+;(function($){
+  $.fn.formatJSON = function(options) {
+    var _options,
+        $disclosure,
+        $json,
+        $jsonList,
+        $separator,
+        append = function(){},
+        isBoolean = function(){},
+        jsonData = {},
+        loopArray = function(){},
+        loopObject = function(){};
+
+    _options = {
+      classes: {
+        array:              "jsonArray",
+        closeBracket:       "jsonCloseBracket",
+        closedGroup:        "jsonClosedGroup",
+        disclosure:         "jsonDisclosure",
+        keyName:            "jsonKeyName",
+        keyNameSeparator:   "jsonKeyNameSeparator",
+        keyword:            "jsonKeyword",
+        number:             "jsonNumber",
+        object:             "jsonObject",
+        openBracket:        "jsonOpenBracket",
+        separator:          "jsonSeparator",
+        string:             "jsonString"
+      },
+      collapse: true,
+      expandRoot: true,
+      jsonListId: "formattedJSON",
+      jsonString: this.text(),
+      events: {
+        complete: function(){},
+        disclosureClicked: function(){}
+      }
+    };
+
+    // Setup the default event handlers.
+    _options.events.disclosureClicked = function() {
+      var $this = $(this),
+          $group = $this.closest("ul"),
+          className = _options.classes.closedGroup;
+      if (! $group.hasClass(className)) {
+        $group
+          .addClass(className)
+          .children(":not(:first-child)")
+          .filter(":not(:last-child)")
+          .toggle();
+        $group
+          .children(":first-child")
+          .append("<i>...</i>");
+        $group
+          .find('.'+_options.classes.disclosure+':first')
+          .text(" + ");
+      } else {
+        $group
+          .children(":first-child")
+          .find("i")
+          .remove();
+        $group
+          .removeClass(className)
+          .children(":not(:visible)")
+          .toggle();
+        $group
+          .find('.'+_options.classes.disclosure+':first')
+          .text(" - ");
+      }
+    };
+
+    // Override out defaults with the user's preferences.
+    _options = $.extend(true, _options, options);
+
+    // Define our utility functions.
+    append = function(parent, child) {
+      child.append($separator.clone());
+      parent.append(child);
+    };
+
+    isBoolean = function(testVal) {
+      return Object.prototype.toString.call(testVal) === "[object Boolean]";
+    };
+
+    // Returns a list item that represents an array.
+    loopArray = function(inArray) {
+      var $bracket,
+          $item,
+          $li,
+          $span,
+          i, j;
+
+      $bracket = $("<li>")
+                  .addClass(_options.classes.openBracket)
+                  .append("[")
+                  .append($disclosure.clone());
+      $item = $("<div>") // The div is going to be replaced.
+                .append($bracket)
+                .append(" ");
+
+      for (i = 0, j = inArray.length; i < j; i += 1) {
+        if ($.isArray(inArray[i])) {
+          $li = $("<li>");
+          $li.append(loopArray(inArray[i]));
+          append($item, $li);
+          continue;
+        }
+
+        if ($.isPlainObject(inArray[i])) {
+          $li = $("<li>");
+          $li.append(loopObject(inArray[i]));
+          append($item, $li);
+          continue;
+        }
+
+        if ($.isNumeric(inArray[i])) {
+          $li = $("<li>").addClass(_options.classes.number);
+          $li.append(inArray[i]);
+          append($item, $li);
+          continue;
+        }
+
+        if (isBoolean(inArray[i]) || inArray[i] === null) {
+          $li = $("<li>").addClass(_options.classes.keyword);
+          if (inArray[i] !== null) {
+            $li.append( (inArray[i]) ? "true" : "false" );
+          } else {
+            $li.append("null");
+          }
+          append($item, $li);
+          continue;
+        }
+
+        // Must be a string!
+        $li = $("<li>").addClass(_options.classes.string);
+        $li.append('"' + inArray[i] + '"');
+        append($item, $li);
+      }
+
+      $bracket = $("<li>")
+                  .addClass(_options.classes.closeBracket)
+                  .append("]");
+
+      $item.find('.' + _options.classes.separator).last().remove();
+
+      $item = $("<ul>")
+              .addClass(_options.classes.array)
+              .append($item.html())
+              .append($bracket)
+              .append(" ");
+
+      return $item;
+    };
+
+    loopObject = function(inObject) {
+      var $bracket,
+          $item,
+          $keyName,
+          $span,
+          $obj,
+          $li,
+          key,
+          prop,
+          value;
+
+      $bracket = $("<li>")
+                  .addClass(_options.classes.openBracket)
+                  .append("{")
+                  .append($disclosure.clone());
+      $item = $("<div>") // The div is going to be replaced.
+                .append($bracket)
+                .append(" ");
+
+      for (prop in inObject) {
+        if (! inObject.hasOwnProperty(prop)) {
+          continue;
+        }
+
+        $keyName = $("<span>")
+                    .addClass(_options.classes.keyName)
+                    .append(prop)
+                    .append(
+                      '<span class="' +
+                      _options.classes.keyNameSeparator +
+                      '">: </span>'
+                    );
+
+        if ($.isArray(inObject[prop])) {
+          $li = $("<li>");
+          $li.append($keyName);
+          $li.append(loopArray(inObject[prop]));
+          append($item, $li);
+          continue;
+        }
+
+        if ($.isPlainObject(inObject[prop])) {
+          $li = $("<li>");
+          $li.append($keyName);
+          $li.append(loopObject(inObject[prop]));
+          append($item, $li);
+        }
+
+        if ($.isNumeric(inObject[prop])) {
+          $li = $("<li>").addClass(_options.classes.number);
+          $li.append($keyName);
+          $li.append(inObject[prop]);
+          append($item, $li);
+          continue;
+        }
+
+        if (isBoolean(inObject[prop]) || inObject[prop] === null) {
+          $li = $("<li>").addClass(_options.classes.keyword);
+          $li.append($keyName);
+          if (inObject[prop] !== null) {
+            $li.append( (inObject[prop]) ? "true" : "false" );
+          } else {
+            $li.append("null");
+          }
+          append($item, $li);
+          continue;
+        }
+
+        // Must be a string!
+        $li = $("<li>").addClass(_options.classes.string);
+        $li.append($keyName);
+        $li.append('"' + inObject[prop] + '"');
+        append($item, $li);
+      }
+
+      $bracket = $("<li>")
+                  .addClass(_options.classes.closeBracket)
+                  .append("}");
+
+      $item.find('.' + _options.classes.separator).last().remove();
+
+      $item = $("<ul>")
+              .addClass(_options.classes.object)
+              .append($item.html())
+              .append($bracket)
+              .append(" ");
+
+      return $item;
+    };
+
+    // Setup our basic DOM objects.
+    jsonData = $.parseJSON(_options.jsonString);
+    $disclosure = $("<span>")
+                    .addClass(_options.classes.disclosure)
+                    .append(" + ");
+    $json = $("<ul>").attr("id", _options.jsonListId);
+    $separator = $("<span>")
+                  .addClass(_options.classes.separator)
+                  .append(", ");
+
+    // Process the data.
+    if ($.isArray(jsonData)) {
+      // JSON is an array of things.
+      $json.append(loopArray(jsonData));
+    } else {
+      // JSON is an object of things.
+      $json.append(loopObject(jsonData));
+    }
+
+    // Bind actions to the event handlers.
+    $json.on(
+      "click",
+      '.'+_options.classes.disclosure,
+      _options.events.disclosureClicked
+    );
+
+    // Insert the result into the document.
+    this.html($json);
+
+    $jsonList = $('#'+_options.jsonListId);
+
+    if (_options.collapse) {
+      $jsonList
+        .find('.'+_options.classes.disclosure)
+        .click();
+    }
+
+    if (_options.expandRoot &&
+      $jsonList.children().first("ul").hasClass(_options.classes.closedGroup)
+      )
+    {
+      $jsonList.find('.'+_options.classes.disclosure+':first').click();
+    }
+
+    _options.events.complete.call(this, this);
+
+    return this;
+  };
+}(jQuery));
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.