Monday, 17 May 2010

Splurging (converting) json into html

   1: $(".profile_image_url").livequery(function () {
   2:             $(".value", this).each(function () { this.innerHTML = "<img src='" + this.innerHTML + "'/>" });
   3:         });
   4:         
   5:         function splurgeToHtml(json) {
   6:             var s = ["<ul>"];
   7:             for (var key in json) {
   8:                 if (json.hasOwnProperty(key)) {
   9:                     var value = json[key];
  10:                     s[s.length] = '<li class="splurged ' + key + '" title="' + key + '"><span class="label">' + key + '</span><span class="value">';
  11:                     if (value instanceof Object) {
  12:                         s[s.length] = splurgeToHtml(value);
  13:                     } else {
  14:                     s[s.length] = (value == null ? "" : value);
  15:                     }
  16:                     s[s.length] = '</span></li>';
  17:                 }
  18:             }
  19:             s[s.length] = "</ul>";
  20:             return s.join("");
  21:         }

Put this here because I’m not using it right now but I don’t want to lose it. This snippet automatically converts a json object into a series of nested <ul> tagswhich can then be styled and jazzed up using css and jquery to your hearts content. Great for a bit of rapid prototyping.