JGaudette
8/26/2015 - 1:15 PM

Greasemonkey Script to format JSON

Greasemonkey Script to format JSON

// ==UserScript==
// @name         Make JSON Pretty
// @version      0.1
// @description  Make JSON look nice
// @author       Jon Gaudette <jgaudette@gmail.com>
// @include      *.json
// @grant        none
// ==/UserScript==

function prettySource(obj) {
	var maxDepth = 250,
		depth = 0,
		root = true,
		sp = "    ",
		dig;
	function objProp (prop) {
		if (prop===null) {
			return "<span style='color:#A6BE88; font-style:italic;'>null</span>,\n";
		}
		var t = (typeof(prop)+"").toLowerCase();
		if (Object.prototype.toString.apply(prop)==="[object Object]" || Object.prototype.toString.apply(prop)==="[object Array]") {
			return branch(prop).replace(/\n/gim,'\n'+sp) + ",\n";
		}
		else if (t==="function") {
			return "<span style='color:#0A0;'>" + (prop+"").replace("<","&lt;").replace(">","&gt;").replace(/function\s?\(/,"function <strong>"+((prop.constructor&&prop.constructor.name)||prop.name||"")+"</strong>(").replace(/\n/gim,'\n    ') + "</span>,\n";
		}
		else if (t==="string") {
			return "<span style='color:#D0D;'>\"" + prop + "\"</span>,\n";
		}
		else if (t==="number") {
			return "<span style='color:#F00;'>" + prop + "</span>,\n";
		}
		else if (t==="boolean") {
			return "<span style='color:#00D;'>" + (prop===true?"true":"false") + "</span>,\n";
		}
		return (prop.toSource || prop.toString)().replace(/^\((new\s)?(.+)\)$/,'$2') + ",\n";
	}
	function branch (what) {
		var wasRoot=root===true, x, dig, text="", m=0;
		root = false;
		if (depth>maxDepth) {
			return "<span style='color:#AAA; font-style:italic;'>[Maximum Depth Reached]</span>";
		}
		depth++;
		if (Object.prototype.toString.apply(what)==="[object Array]") {
			text = "<pre style='color:#555; display:"+(wasRoot===false?"inline":"block")+"; margin:0; padding:0;'><strong>[</strong>\n";
			for (x=0; x<what.length; x++) {
				dig = (x+"# ").length;
				text += sp.substring(0,4-dig) + "<span style='color:#ABC; font-style:italic;'>#" + x + "</span> " + objProp(what[x]);
			}
			return text.replace(/\,\n$/,'\n') + "<strong>]</strong></pre>";
		}
		else if (Object.prototype.toString.apply(what)==="[object Object]") {
			text = "<pre style='color:#555; display:"+(wasRoot===false?"inline":"block")+"; margin:0; padding:0;'><strong>{</strong>\n";
			for (x in what) {
				if (what.hasOwnProperty(x)) {
					m = Math.max(m,(x+"").length);
				}
			}
			m += 1;
			for (x in what) {
				if (what.hasOwnProperty(x)) {
					text += sp + "<span style='color:#089;'>" + x + "</span>"+(new Array(m-(x+"").length).join(" "))+" : " + objProp(what[x]);
				}
			}
			return text.replace(/\,\n$/,'\n') + "<strong>}</strong></pre>";
		}
	}
	var r = branch(obj);
	sp = root = branch = objProp = null;
	return r;
}
/*START*/
if (document.getElementById('jsonify_pretty_print')) {
  location.href += "";
}
else {
  var src = '',
       relaxedMode = true;
       txt = document.body.textContent.split('\n').join(' ').replace(/^[^\{\[]*/gim,'').replace(/[^\}\]]*$/gim,'');
  if (window.JSON && window.JSON.parse) {
    try {
      src = prettySource(JSON.parse(txt));
    } catch(err) {
      relaxedMode = confirm('Invalid JSON; strict parse failed.\n\nParse in relaxed mode?')===true;
      if (!relaxedMode) {
        return false;
      }
    }
  }
  if (relaxedMode===true) {
    try {
      src = prettySource(eval('('+txt+')'));
    } catch(err) {
      alert('Invalid JSON; relaxed parse failed.\n\nWARNING: This JSON output will not parse in most web browsers.');
      return false;
    }
  }
  document.open('text/html');
  document.write('<html><body><span id="jsonify_pretty_print"><\/span><pre>'+src+'<\/pre><\/body><\/html>');
  document.close();
}