Skip to content

A Swiss Army knife for developers.

JsonHelper.IsValid is not matching some JSON structures (#363)

Anirudh Khannad99d8ca08c62
diff --git a/src/dev/impl/DevToys/Helpers/JsonHelper.cs b/src/dev/impl/DevToys/Helpers/JsonHelper.cs
index 84e3ae930..913b9d1d6 100644
--- a/src/dev/impl/DevToys/Helpers/JsonHelper.cs
+++ b/src/dev/impl/DevToys/Helpers/JsonHelper.cs
@@ -17,34 +17,26 @@ namespace DevToys.Helpers
/// </summary>
internal static bool IsValid(string? input)
{
- if (string.IsNullOrWhiteSpace(input))
+ input = input?.Trim();
+
+ if (input == null)
{
- return false;
+ return true;
}
- input = input!.Trim();
-
- if ((input.StartsWith("{") && input.EndsWith("}")) //For object
- || (input.StartsWith("[") && input.EndsWith("]"))) //For array
+ try
{
- try
- {
- var jtoken = JToken.Parse(input);
- return jtoken is not null;
- }
- catch (JsonReaderException)
- {
- // Exception in parsing json. It likely mean the text isn't a JSON.
- return false;
- }
- catch (Exception ex) //some other exception
- {
- Logger.LogFault("Check is string if JSON", ex);
- return false;
- }
+ var jtoken = JToken.Parse(input);
+ return jtoken is not null;
}
- else
+ catch (JsonReaderException)
+ {
+ // Exception in parsing json. It likely mean the text isn't a JSON.
+ return false;
+ }
+ catch (Exception ex) //some other exception
{
+ Logger.LogFault("Check if string is JSON", ex);
return false;
}
}
@@ -54,14 +46,14 @@ namespace DevToys.Helpers
/// </summary>
internal static string Format(string? input, Indentation indentationMode)
{
- if (!IsValid(input))
+ if (input == null || !IsValid(input))
{
return string.Empty;
}
try
{
- var jtoken = JToken.Parse(input!);
+ var jtoken = JToken.Parse(input);
if (jtoken is not null)
{
var stringBuilder = new StringBuilder();
diff --git a/src/tests/DevToys.Tests/Helpers/JsonHelperTests.cs b/src/tests/DevToys.Tests/Helpers/JsonHelperTests.cs
index b83ef28c1..41d337249 100644
--- a/src/tests/DevToys.Tests/Helpers/JsonHelperTests.cs
+++ b/src/tests/DevToys.Tests/Helpers/JsonHelperTests.cs
@@ -8,7 +8,9 @@ namespace DevToys.Tests.Helpers
public class JsonHelperTests
{
[DataTestMethod]
- [DataRow(null, false)]
+ [DataRow(null, true)]
+ [DataRow("\"foo\"", true)]
+ [DataRow("123", true)]
[DataRow("", false)]
[DataRow(" ", false)]
[DataRow(" { } ", true)]