Created
July 29, 2014 05:26
-
-
Save badmotorfinger/73cbb60329cd8b790091 to your computer and use it in GitHub Desktop.
A compact JSON beautifier
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
// 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