A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
JSON Formatter can now sort properties alphabetically. (#578)
Etienne Baudouxc9e9cb0492c6
diff --git a/src/dev/impl/DevToys/Helpers/JsonYaml/JsonHelper.cs b/src/dev/impl/DevToys/Helpers/JsonYaml/JsonHelper.csindex ea95d5252..cf4fe2a6f 100644--- a/src/dev/impl/DevToys/Helpers/JsonYaml/JsonHelper.cs+++ b/src/dev/impl/DevToys/Helpers/JsonYaml/JsonHelper.cs@@ -2,6 +2,7 @@using System;using System.IO;+using System.Linq;using System.Text;using DevToys.Core;using DevToys.Helpers.JsonYaml.Core;@@ -52,7 +53,7 @@ namespace DevToys.Helpers.JsonYaml/// <summary>/// Format a string to the specified JSON format./// </summary>- internal static string Format(string? input, Indentation indentationMode)+ internal static string Format(string? input, Indentation indentationMode, bool sortProperties){if (input == null || !IsValid(input)){@@ -68,53 +69,55 @@ namespace DevToys.Helpers.JsonYamlLineInfoHandling = LineInfoHandling.Load};+ JObject jObject;using (var jsonReader = new JsonTextReader(new StringReader(input))){jsonReader.DateParseHandling = DateParseHandling.None;jsonReader.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;- var jtoken = JToken.ReadFrom(jsonReader, jsonLoadSettings);- if (jtoken is not null)+ jObject = JObject.Load(jsonReader, jsonLoadSettings);+ }++ if (sortProperties)+ {+ SortJsonPropertiesAlphabetically(jObject);+ }++ var stringBuilder = new StringBuilder();+ using (var stringWriter = new StringWriter(stringBuilder))+ using (var jsonTextWriter = new JsonTextWriter(stringWriter))+ {+ switch (indentationMode){- var stringBuilder = new StringBuilder();- using (var stringWriter = new StringWriter(stringBuilder))- using (var jsonTextWriter = new JsonTextWriter(stringWriter))- {- switch (indentationMode)- {- case Indentation.TwoSpaces:- jsonTextWriter.Formatting = Formatting.Indented;- jsonTextWriter.IndentChar = ' ';- jsonTextWriter.Indentation = 2;- break;- case Indentation.FourSpaces:- jsonTextWriter.Formatting = Formatting.Indented;- jsonTextWriter.IndentChar = ' ';- jsonTextWriter.Indentation = 4;- break;- case Indentation.OneTab:- jsonTextWriter.Formatting = Formatting.Indented;- jsonTextWriter.IndentChar = '\t';- jsonTextWriter.Indentation = 1;- break;- case Indentation.Minified:- jsonTextWriter.Formatting = Formatting.None;- break;- default:- throw new NotSupportedException();- }-- jsonTextWriter.DateFormatHandling = DateFormatHandling.IsoDateFormat;- jsonTextWriter.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;-- jtoken.WriteTo(jsonTextWriter);- }-- return stringBuilder.ToString();+ case Indentation.TwoSpaces:+ jsonTextWriter.Formatting = Formatting.Indented;+ jsonTextWriter.IndentChar = ' ';+ jsonTextWriter.Indentation = 2;+ break;+ case Indentation.FourSpaces:+ jsonTextWriter.Formatting = Formatting.Indented;+ jsonTextWriter.IndentChar = ' ';+ jsonTextWriter.Indentation = 4;+ break;+ case Indentation.OneTab:+ jsonTextWriter.Formatting = Formatting.Indented;+ jsonTextWriter.IndentChar = '\t';+ jsonTextWriter.Indentation = 1;+ break;+ case Indentation.Minified:+ jsonTextWriter.Formatting = Formatting.None;+ break;+ default:+ throw new NotSupportedException();}++ jsonTextWriter.DateFormatHandling = DateFormatHandling.IsoDateFormat;+ jsonTextWriter.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;++ jObject.WriteTo(jsonTextWriter);}- return string.Empty;+ return stringBuilder.ToString();}catch (JsonReaderException ex){@@ -193,5 +196,23 @@ namespace DevToys.Helpers.JsonYamlreturn string.Empty;}}++ private static void SortJsonPropertiesAlphabetically(JObject jObject)+ {+ var properties = jObject.Properties().ToList();+ foreach (JProperty? property in properties)+ {+ property.Remove();+ }++ foreach (JProperty? property in properties.OrderBy(p => p.Name))+ {+ jObject.Add(property);+ if (property.Value is JObject obj)+ {+ SortJsonPropertiesAlphabetically(obj);+ }+ }+ }}}diff --git a/src/dev/impl/DevToys/LanguageManager.cs b/src/dev/impl/DevToys/LanguageManager.csindex 930bee340..e92e934b0 100644--- a/src/dev/impl/DevToys/LanguageManager.cs+++ b/src/dev/impl/DevToys/LanguageManager.cs@@ -1359,6 +1359,11 @@ namespace DevToys/// Gets the resource SearchKeywords./// </summary>public string SearchKeywords => _resources.GetString("SearchKeywords");++ /// <summary>+ /// Gets the resource SortProperties.+ /// </summary>+ public string SortProperties => _resources.GetString("SortProperties");}public class JsonYamlStrings : ObservableObjectdiff --git a/src/dev/impl/DevToys/Strings/en-US/JsonFormatter.resw b/src/dev/impl/DevToys/Strings/en-US/JsonFormatter.reswindex 16e51b8b8..e3a5446eb 100644--- a/src/dev/impl/DevToys/Strings/en-US/JsonFormatter.resw+++ b/src/dev/impl/DevToys/Strings/en-US/JsonFormatter.resw@@ -156,4 +156,7 @@<data name="SearchKeywords" xml:space="preserve"><value /></data>+ <data name="SortProperties" xml:space="preserve">+ <value>Sort JSON properties alphabetically</value>+ </data></root>\ No newline at end of filediff --git a/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderToolViewModel.cs b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderToolViewModel.csindex c2c36181d..63eb8980b 100644--- a/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderToolViewModel.cs+++ b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderToolViewModel.cs@@ -118,8 +118,8 @@ namespace DevToys.ViewModels.Tools.JwtDecoderEncoder{var handler = new JwtSecurityTokenHandler();JwtSecurityToken jwtSecurityToken = handler.ReadJwtToken(input);- header = JsonHelper.Format(jwtSecurityToken.Header.SerializeToJson(), Indentation.TwoSpaces);- payload = JsonHelper.Format(jwtSecurityToken.Payload.SerializeToJson(), Indentation.TwoSpaces);+ header = JsonHelper.Format(jwtSecurityToken.Header.SerializeToJson(), Indentation.TwoSpaces, sortProperties: false);+ payload = JsonHelper.Format(jwtSecurityToken.Payload.SerializeToJson(), Indentation.TwoSpaces, sortProperties: false);}catch (Exception ex){diff --git a/src/dev/impl/DevToys/ViewModels/Tools/Formatters/JsonFormatter/JsonFormatterToolViewModel.cs b/src/dev/impl/DevToys/ViewModels/Tools/Formatters/JsonFormatter/JsonFormatterToolViewModel.csindex fc816be36..faea71f53 100644--- a/src/dev/impl/DevToys/ViewModels/Tools/Formatters/JsonFormatter/JsonFormatterToolViewModel.cs+++ b/src/dev/impl/DevToys/ViewModels/Tools/Formatters/JsonFormatter/JsonFormatterToolViewModel.cs@@ -30,6 +30,15 @@ namespace DevToys.ViewModels.Tools.JsonFormatterisRoaming: true,defaultValue: Models.Indentation.TwoSpaces);+ /// <summary>+ /// Whether properties within the JSON should be sorted alphabetically or not.+ /// </summary>+ private static readonly SettingDefinition<bool> SortProperties+ = new(+ name: $"{nameof(JsonFormatterToolViewModel)}.{nameof(SortProperties)}",+ isRoaming: true,+ defaultValue: false);+private readonly IMarketingService _marketingService;private readonly Queue<string> _formattingQueue = new();@@ -74,6 +83,24 @@ namespace DevToys.ViewModels.Tools.JsonFormatterModels.IndentationDisplayPair.Minified,};++ /// <summary>+ /// Gets or sets the whether properties within the JSON should be sorted alphabetically or not.+ /// </summary>+ internal bool IsSortProperties+ {+ get => SettingsProvider.GetSetting(SortProperties);+ set+ {+ if (IsSortProperties != value)+ {+ SettingsProvider.SetSetting(SortProperties, value);+ OnPropertyChanged();+ QueueFormatting();+ }+ }+ }+/// <summary>/// Gets or sets the input text./// </summary>@@ -121,7 +148,7 @@ namespace DevToys.ViewModels.Tools.JsonFormatterwhile (_formattingQueue.TryDequeue(out string? text)){- string? result = JsonHelper.Format(text, IndentationMode.Value);+ string? result = JsonHelper.Format(text, IndentationMode.Value, IsSortProperties);if (result != null){ThreadHelper.RunOnUIThreadAsync(ThreadPriority.Low, () =>diff --git a/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/Base64TextEncoderDecoder/Base64EncoderDecoderToolPage.xaml b/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/Base64TextEncoderDecoder/Base64EncoderDecoderToolPage.xamlindex 1837d709b..d1b5aa56f 100644--- a/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/Base64TextEncoderDecoder/Base64EncoderDecoderToolPage.xaml+++ b/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/Base64TextEncoderDecoder/Base64EncoderDecoderToolPage.xaml@@ -38,7 +38,6 @@<StackPanel Spacing="4" Grid.Row="0" ><TextBlock Style="{StaticResource SubTitleTextBlock}" Text="{x:Bind ViewModel.Strings.ConfigurationTitle}" /><controls:ExpandableSettingControl- Grid.Row="1"Title="{x:Bind ViewModel.Strings.ConversionTitle}"Description="{x:Bind ViewModel.Strings.ConversionDescription}"><controls:ExpandableSettingControl.Icon>@@ -51,7 +50,6 @@</controls:ExpandableSettingControl><controls:ExpandableSettingControlx:Name="EncodingSetting"- Grid.Row="2"Title="{x:Bind ViewModel.Strings.EncodingTitle}"Description="{x:Bind ViewModel.Strings.EncodingDescription}"><controls:ExpandableSettingControl.Icon>diff --git a/src/dev/impl/DevToys/Views/Tools/Formatters/JsonFormatter/JsonFormatterToolPage.xaml b/src/dev/impl/DevToys/Views/Tools/Formatters/JsonFormatter/JsonFormatterToolPage.xamlindex 789f4e2ac..2ec708db5 100644--- a/src/dev/impl/DevToys/Views/Tools/Formatters/JsonFormatter/JsonFormatterToolPage.xaml+++ b/src/dev/impl/DevToys/Views/Tools/Formatters/JsonFormatter/JsonFormatterToolPage.xaml@@ -64,6 +64,15 @@SelectedValue="{x:Bind ViewModel.IndentationMode, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></ComboBox></controls:ExpandableSettingControl>+ <controls:ExpandableSettingControl+ Title="{x:Bind ViewModel.Strings.SortProperties}">+ <controls:ExpandableSettingControl.Icon>+ <FontIcon Glyph="" />+ </controls:ExpandableSettingControl.Icon>+ <ToggleSwitch+ Style="{StaticResource RightAlignedToggleSwitchStyle}"+ IsOn="{x:Bind ViewModel.IsSortProperties, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />+ </controls:ExpandableSettingControl></StackPanel><Grid Grid.Row="1">diff --git a/src/tests/DevToys.Tests/Helpers/JsonHelperTests.cs b/src/tests/DevToys.Tests/Helpers/JsonHelperTests.csindex 653425053..1ec66633c 100644--- a/src/tests/DevToys.Tests/Helpers/JsonHelperTests.cs+++ b/src/tests/DevToys.Tests/Helpers/JsonHelperTests.cs@@ -29,7 +29,7 @@ namespace DevToys.Tests.Helpers[DataRow(" { \"foo\": 123 } ", "{\r\n \"foo\": 123\r\n}")]public void FormatTwoSpaces(string input, string expectedResult){- Assert.AreEqual(expectedResult, JsonHelper.Format(input, Indentation.TwoSpaces));+ Assert.AreEqual(expectedResult, JsonHelper.Format(input, Indentation.TwoSpaces, sortProperties: false));}[DataTestMethod]@@ -40,7 +40,7 @@ namespace DevToys.Tests.Helpers[DataRow(" { \"foo\": 123 } ", "{\r\n \"foo\": 123\r\n}")]public void FormatFourSpaces(string input, string expectedResult){- Assert.AreEqual(expectedResult, JsonHelper.Format(input, Indentation.FourSpaces));+ Assert.AreEqual(expectedResult, JsonHelper.Format(input, Indentation.FourSpaces, sortProperties: false));}[DataTestMethod]@@ -51,7 +51,7 @@ namespace DevToys.Tests.Helpers[DataRow(" { \"foo\": 123 } ", "{\r\n\t\"foo\": 123\r\n}")]public void FormatOneTab(string input, string expectedResult){- Assert.AreEqual(expectedResult, JsonHelper.Format(input, Indentation.OneTab));+ Assert.AreEqual(expectedResult, JsonHelper.Format(input, Indentation.OneTab, sortProperties: false));}[DataTestMethod]@@ -62,14 +62,21 @@ namespace DevToys.Tests.Helpers[DataRow(" { \"foo\": 123 } ", "{\"foo\":123}")]public void FormatMinified(string input, string expectedResult){- Assert.AreEqual(expectedResult, JsonHelper.Format(input, Indentation.Minified));+ Assert.AreEqual(expectedResult, JsonHelper.Format(input, Indentation.Minified, sortProperties: false));}[DataTestMethod][DataRow("{ \"Date\": \"2012-04-21T18:25:43-05:00\" }", "{\"Date\":\"2012-04-21T18:25:43-05:00\"}")]public void FormatDoesNotAlterateDateTimes(string input, string expectedResult){- Assert.AreEqual(expectedResult, JsonHelper.Format(input, Indentation.Minified));+ Assert.AreEqual(expectedResult, JsonHelper.Format(input, Indentation.Minified, sortProperties: false));+ }++ [DataTestMethod]+ [DataRow("{\"Email\":\"[email protected]\",\"Website\":\"http://samplewebsite.com\",\"Name\":\"John Smith\",\"Phone\":\"(50)345872\"}", "{\"Email\":\"[email protected]\",\"Name\":\"John Smith\",\"Phone\":\"(50)345872\",\"Website\":\"http://samplewebsite.com\"}")]+ public void FormatSortPropertiesAlphabetically(string input, string expectedResult)+ {+ Assert.AreEqual(expectedResult, JsonHelper.Format(input, Indentation.Minified, sortProperties: true));}[DataTestMethod]