w4c-workflows-api/Services/Nodes/Executors/NodeJsonPath.cs
2026-09-12 01:02:46 +03:00

30 lines
931 B
C#

using System.Text.Json.Nodes;
namespace w4c_workflows.Services.Nodes.Executors;
/// <summary>
/// Resolves an item field by name, with optional dot notation for nested
/// objects (<c>user.name</c> → <c>{ "user": { "name": … } }</c>). Missing paths
/// return null, never throw, so sort/dedup/aggregate treat them as empty.
/// </summary>
internal static class NodeJsonPath
{
public static JsonNode? Read(JsonObject json, string? path, bool dotNotation)
{
if (string.IsNullOrEmpty(path))
return null;
if (!dotNotation || !path.Contains('.'))
return json.TryGetPropertyValue(path, out var direct) ? direct : null;
JsonNode? current = json;
foreach (var segment in path.Split('.'))
{
if (current is not JsonObject obj || !obj.TryGetPropertyValue(segment, out current))
return null;
}
return current;
}
}