using Jtr.Parsing.Json; using Jtr.Parsing.Json.Syntax; using Jtr.Parsing; using Jtr.Parsing.Extensions; namespace Jtr.Tools; public static partial class JsonFormatter { private static VisitorContainer Visitors { get; } = new(); static JsonFormatter() { Visitors.Register(PrintArray); Visitors.Register(PrintObject); Visitors.Register(PrintString); Visitors.Register(PrintNumber); Visitors.Register(PrintBool); Visitors.Register(PrintNull); } public static string Format(string input, Context? context) { var node = JsonParser.Parse("", input); return Format(node, context); } public static string Format(IJsonSyntax visitee, Context? context = null) { context ??= new(); Visitors[visitee.GetType()](visitee, context); return context.Builder.ToString(); } private static void PrintArray(IJsonSyntax visitee, Context context) { var array = visitee.As(); context.Builder.Append($"[{context.NewLine}"); context.IncrementDepth(); for (var i = 0; i < array.Elements.Length; i++) { var node = array.Elements[i]; context.Builder.Append(context.Indent); Visitors[node.GetType()](node, context); if (i < array.Elements.Length - 1) context.Builder.Append($",{context.NewLine}"); } context.DecrementDepth(); context.Builder.Append($"{context.NewLine}{context.Indent}]"); } private static void PrintObject(IJsonSyntax visitee, Context context) { var @object = visitee.As(); context.Builder.Append($"{{{context.NewLine}"); context.IncrementDepth(); var count = @object.Properties.Length; for (var i = 0; i < count; i++) { var property = @object.Properties.ElementAt(i); context.Builder.Append($"{context.Indent}\"{property.Key.Lexeme}\":{context.Space}"); Visitors[property.Value.GetType()](property.Value, context); if (i < count - 1) context.Builder.Append($",{context.NewLine}"); } context.DecrementDepth(); context.Builder.Append($"{context.NewLine}{context.Indent}}}"); } private static void PrintString(IJsonSyntax visitee, Context context) { var @string = visitee.As(); context.Builder.Append($"\"{@string.Token.Lexeme}\""); } private static void PrintNumber(IJsonSyntax visitee, Context context) { var number = visitee.As(); context.Builder.Append($"{number.Value}"); } private static void PrintBool(IJsonSyntax visitee, Context context) { var @bool = visitee.As(); context.Builder.Append($"{@bool.Value.ToString().ToLower()}"); } private static void PrintNull(IJsonSyntax visitee, Context context) { context.Builder.Append("null"); } }