Skip to content

Instantly share code, notes, and snippets.

@badmotorfinger
Created July 29, 2014 05:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save badmotorfinger/73cbb60329cd8b790091 to your computer and use it in GitHub Desktop.
Save badmotorfinger/73cbb60329cd8b790091 to your computer and use it in GitHub Desktop.
A compact JSON beautifier
// Highly compact JSON beautifier/formatter. Not very efficient and could definitely be improved. The main issue is with
// the number of allocations and memory presure being placed on the heap and garbage collector if the input is large.
// It is the shortest in terms of code size though.
// Source: http://stackoverflow.com/questions/4580397/json-formatter-in-c/24782322#24782322
private const string INDENT_STRING = " ";
static string FormatJson(string json) {
int indentation = 0;
int quoteCount = 0;
var result =
from ch in json
let quotes = ch == '"' ? quoteCount++ : quoteCount
let lineBreak = ch == ',' && quotes % 2 == 0 ? ch + Environment.NewLine + String.Concat(Enumerable.Repeat(INDENT_STRING, indentation)) : null
let openChar = ch == '{' || ch == '[' ? ch + Environment.NewLine + String.Concat(Enumerable.Repeat(INDENT_STRING, ++indentation)) : ch.ToString()
let closeChar = ch == '}' || ch == ']' ? Environment.NewLine + String.Concat(Enumerable.Repeat(INDENT_STRING, --indentation)) + ch : ch.ToString()
select lineBreak == null
? openChar.Length > 1
? openChar
: closeChar
: lineBreak;
return String.Concat(result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment