From 4e85c33589ef9e3a2f7e4c6622506fc2011553a7 Mon Sep 17 00:00:00 2001 From: Terry Hearst Date: Mon, 1 Jan 2024 15:11:59 -0500 Subject: [PATCH] Auto format JSON --- Config.cs | 2 +- JsonHelper.cs | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 JsonHelper.cs diff --git a/Config.cs b/Config.cs index fcbf48a..ccf4460 100644 --- a/Config.cs +++ b/Config.cs @@ -94,7 +94,7 @@ namespace DiamondTimeViewer break; } node.Add("hideSilver", HideSilver ? "true" : "false"); - File.WriteAllText(GetConfigPath(), node.ToString()); + File.WriteAllText(GetConfigPath(), JsonHelper.FormatJson(node.ToString(), "\t")); } public static string GetConfigPath() diff --git a/JsonHelper.cs b/JsonHelper.cs new file mode 100644 index 0000000..b7e923b --- /dev/null +++ b/JsonHelper.cs @@ -0,0 +1,34 @@ +using System; +using System.Linq; + +namespace DiamondTimeViewer +{ + public class JsonHelper + { + /* + * Code taken from: https://stackoverflow.com/a/57100143 + */ + 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); + } + } +}