Fixed a JSON exception

This commit is contained in:
Anon 2026-03-26 19:16:48 +01:00
parent 747662ea8c
commit 7a75328f0a

View file

@ -1,3 +1,4 @@
using System;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
@ -23,10 +24,46 @@ public static class Json
public static JsonNode? ParseJson(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return null;
ReadOnlySpan<char> text = json.AsSpan().TrimStart();
if (!LooksLikeJson(text))
return JsonValue.Create(json);
try { return JsonNode.Parse(json); }
catch (JsonException) { return JsonValue.Create(json); }
}
private static bool LooksLikeJson(ReadOnlySpan<char> text)
{
if (text.IsEmpty)
return false;
return text[0] switch
{
'{' or '"' => true,
'[' => LooksLikeJsonArray(text[1..]),
'-' => text.Length > 1 && char.IsAsciiDigit(text[1]),
>= '0' and <= '9' => true,
't' or 'f' or 'n' => true,
_ => false
};
}
private static bool LooksLikeJsonArray(ReadOnlySpan<char> text)
{
text = text.TrimStart();
if (text.IsEmpty)
return false;
return text[0] switch
{
']' or '{' or '[' or '"' => true,
'-' => text.Length > 1 && char.IsAsciiDigit(text[1]),
>= '0' and <= '9' => true,
't' or 'f' or 'n' => true,
_ => false
};
}
/// <summary>
/// Escape a string for embedding inside a JSON string literal.
/// Uses System.Text.Json serialization and strips the surrounding quotes.