-
-
Save thegoleffect/592830 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
var sys = require("sys"), | |
fs = require("fs"); | |
var indented = ""; | |
(function (json) { | |
indented = /(^[\t ]*)/.exec(json)[0] || ""; | |
try { | |
var parsed = JSON.parse(json); | |
} catch (ex) { | |
var parsed = process.compile("("+json+")", "json"); | |
} | |
// process.stdio.write(sys.inspect(parsed).replace(/(\{|,) ([\w\d_]+):/g, "$1 '$2':")); | |
sys.puts(pretty(parsed, null, null, indented || "").replace(/[\t ]+(\n|$)/g, '$1')); | |
})(process.env.TM_SELECTED_TEXT ? process.env.TM_SELECTED_TEXT : fs.readFileSync(process.env.TM_FILEPATH)); | |
function pretty (obj, depth, name) { | |
name = name || ""; | |
depth = depth || 0; | |
if (typeof obj === "function") return "null"; | |
if (typeof obj === "object") { | |
if (!obj) return "null"; | |
else if (obj instanceof Date) obj = JSON.stringify(obj); | |
else if ( | |
obj instanceof Boolean || | |
obj instanceof String || | |
obj instanceof Number | |
) obj = obj.valueOf(); | |
} | |
// Primitive types cannot have properties | |
switch (typeof obj) { | |
case "undefined": | |
case "string": | |
case "number": | |
case "boolean": | |
return JSON.stringify(obj); | |
} | |
var TAB = "\n" + indent(depth), | |
out = [], | |
inline, broken, brace; | |
if (Array.isArray(obj)) { | |
for (var i = 0, l = obj.length; i < l; i ++) { | |
out.push((i ? ", " : "[ ") + pretty(obj[i], depth + 1)); | |
} | |
if (i === 0) out.push("["); | |
brace = "]"; | |
} else { | |
var sawFirst = false, out = []; | |
for (var i in obj) { | |
out.push((sawFirst ? ", " : "{ ") + JSON.stringify(i) + " : " + pretty(obj[i], depth + 1, i)); | |
sawFirst = true; | |
} | |
if (!sawFirst) out.push("{"); | |
brace = "}"; | |
} | |
inline = out.join("") + " " + brace; | |
inline = inline.replace(/\[ \]/g, "[]").replace(/\{ \}/g, "{}"); | |
broken = (depth && name ? TAB : indented) + out.join(TAB) + TAB + brace; | |
return (depth < 5 && (TAB + name + inline).length < 75) ? inline : broken; | |
} | |
function indent (depth) { | |
var s = indented || ""; | |
while (depth --) s += " "; | |
return s; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment