Skip to content

Instantly share code, notes, and snippets.

@kamranayub
Last active September 25, 2015 02:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamranayub/846861 to your computer and use it in GitHub Desktop.
Save kamranayub/846861 to your computer and use it in GitHub Desktop.
Formats a valid JSON string into a pretty output
/// <summary>
/// Formats a JSON string by walking through it and examining the contents.
/// </summary>
/// <param name="json">Unformatted JSON string, expects valid JSON with quoted keys and no whitespace.</param>
/// <returns>Formatted JSON string</returns>
/// <remarks>
/// [ { should have line breaks and tabs after them
/// ] } should have line breaks and tabs before them
/// : should have a space after it
/// , should have a line break and tab
/// </remarks>
public static string PrettyJson(this string json) {
var sbOutput = new StringBuilder();
var tokens = new char[] {'{','}','[',']',',',':'};
bool inQuotes = false;
int level = 0;
Action Blockify = () => {
var chars = new char[level];
for (var i = 0; i < level; i++)
chars[i] = '\t';
sbOutput.AppendLine();
sbOutput.Append(chars);
};
for (var i = 0; i < json.Length; i++) {
var curChar = json[i];
// Ignore escaped quotes
if (curChar == '"' && json[i-1] != '\\')
inQuotes = !inQuotes;
// Ignore anything in quotes or that isn't a token
if (inQuotes || !tokens.Contains(curChar)) {
sbOutput.Append(curChar);
continue;
}
if (curChar == '{' || curChar == '[' || curChar == ',') {
if (curChar != ',') level++;
sbOutput.Append(curChar);
Blockify();
}
else if (curChar == '}' || curChar == ']') {
level--;
Blockify();
sbOutput.Append(curChar);
}
else if (curChar == ':') {
sbOutput.Append(curChar + " ");
}
}
return sbOutput.ToString();
}
// Formats a well-formed JSON string into a pretty version
String.prototype.prettyJson = function() {
var json = this,
output = "",
tokens = ['{', '}', '[', ']', ',', ':'],
inQuotes = false,
level = 0,
blockify = function() {
output += '\r\n';
for (var k = 0; k < level; k++) {
output += ' ';
}
};
for (var i = 0; i < json.length; i++) {
var curChar = json.charAt(i);
// Ignore escaped quotes
if (curChar === '"' && json.charAt(i - 1) !== '\\') {
inQuotes = !inQuotes;
}
// Ignore anything in quotes or that isn't a token
if (inQuotes || tokens.indexOf(curChar) === -1) {
output += curChar;
continue;
}
if (curChar === '{' || curChar === '[' || curChar === ',') {
if (curChar !== ',') level++;
output += curChar;
blockify();
} else if (curChar === '}' || curChar === ']') {
level--;
blockify();
output += curChar;
} else if (curChar === ':') {
output += curChar + " ";
}
}
return output;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment