Created
July 31, 2013 16:36
-
-
Save geraintluff/6123707 to your computer and use it in GitHub Desktop.
This file contains 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
function prettyJson(data) { | |
var json = JSON.stringify(data, null, "\t"); | |
function compactJson(json) { | |
try { | |
var compact = JSON.stringify(JSON.parse(json)); | |
var parts = compact.split('"'); | |
for (var i = 0; i < parts.length; i++) { | |
var part = parts[i]; | |
part = part.replace(/:/g, ': '); | |
part = part.replace(/,/g, ', '); | |
parts[i] = part; | |
i++; | |
while (i < parts.length && parts[i].charAt(parts[i].length - 1) == "\\") { | |
i++; | |
} | |
} | |
return parts.join('"'); | |
} catch (e) { | |
return json; | |
} | |
} | |
json = json.replace(/\{[^\{,}]*\}/g, compactJson); // Objects with a single simple property | |
json = json.replace(/\[[^\[,\]]*\]/g, compactJson); // Arrays with a single simple item | |
json = json.replace(/\[[^\{\[\}\]]*\]/g, compactJson); // Arrays containing only scalar items | |
return json; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment