Auto format JSON

This commit is contained in:
Terry Hearst 2024-01-01 15:11:59 -05:00
parent b3ad602d09
commit 4e85c33589
2 changed files with 35 additions and 1 deletions

View file

@ -94,7 +94,7 @@ namespace DiamondTimeViewer
break; break;
} }
node.Add("hideSilver", HideSilver ? "true" : "false"); node.Add("hideSilver", HideSilver ? "true" : "false");
File.WriteAllText(GetConfigPath(), node.ToString()); File.WriteAllText(GetConfigPath(), JsonHelper.FormatJson(node.ToString(), "\t"));
} }
public static string GetConfigPath() public static string GetConfigPath()

34
JsonHelper.cs Normal file
View file

@ -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);
}
}
}