Skip to content

Instantly share code, notes, and snippets.

@hoangitk
Created November 23, 2022 03:23
Show Gist options
  • Save hoangitk/3df9a76d50e6a620fc45cd631a45f93d to your computer and use it in GitHub Desktop.
Save hoangitk/3df9a76d50e6a620fc45cd631a45f93d to your computer and use it in GitHub Desktop.
[Simple FormatJson] #json #csharp
/*
Credit: https://stackoverflow.com/questions/4580397/json-formatter-in-c
*/
public static string FormatJson(string json, string indent = " ")
{
var indentation = 0;
var quoteCount = 0;
var escapeCount = 0;
var result =
from ch in json ?? string.Empty
let escaped = (ch == '\\' ? escapeCount++ : escapeCount > 0 ? escapeCount-- : escapeCount) > 0
let quotes = ch == '"' && !escaped ? quoteCount++ : quoteCount
let unquoted = quotes % 2 == 0
let colon = ch == ':' && unquoted ? ": " : null
let nospace = char.IsWhiteSpace(ch) && unquoted ? string.Empty : null
let lineBreak = ch == ',' && unquoted ? ch + Environment.NewLine + string.Concat(Enumerable.Repeat(indent, indentation)) : null
let openChar = (ch == '{' || ch == '[') && unquoted ? ch + Environment.NewLine + string.Concat(Enumerable.Repeat(indent, ++indentation)) : ch.ToString()
let closeChar = (ch == '}' || ch == ']') && unquoted ? Environment.NewLine + string.Concat(Enumerable.Repeat(indent, --indentation)) + ch : ch.ToString()
select colon ?? nospace ?? lineBreak ?? (
openChar.Length > 1 ? openChar : closeChar
);
return string.Concat(result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment