Skip to content

Commit e6a02c4

Browse files
committed
Convenient extension method to search for a node in a json doc that corresponds to a certain path. If the node is not present in the doc, fallback to a second path. If this second path is not present, fallback to a third path and so on.
1 parent a1f4508 commit e6a02c4

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

src/GitReleaseManager.Core/Extensions/JsonExtensions.cs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,18 @@
11
using System;
2+
using System.Collections.Generic;
23
using System.Linq;
34
using System.Text.Json;
45

56
namespace GitReleaseManager.Core.Extensions
67
{
78
internal static class JsonExtensions
89
{
10+
/// <summary>
11+
/// Get a JsonElement from a path. Each level in the path is seperated by a dot.
12+
/// </summary>
13+
/// <param name="jsonElement">The parent Json element.</param>
14+
/// <param name="path">The path of the desired child element.</param>
15+
/// <returns>The child element.</returns>
916
public static JsonElement GetJsonElement(this JsonElement jsonElement, string path)
1017
{
1118
if (jsonElement.ValueKind is JsonValueKind.Null || jsonElement.ValueKind is JsonValueKind.Undefined)
@@ -39,6 +46,36 @@ public static JsonElement GetJsonElement(this JsonElement jsonElement, string pa
3946
return jsonElement;
4047
}
4148

49+
/// <summary>
50+
/// Get the first JsonElement matching a path from the provided list of paths.
51+
/// </summary>
52+
/// <param name="jsonElement">The parent Json element.</param>
53+
/// <param name="paths">The path of the desired child element.</param>
54+
/// <returns>The child element.</returns>
55+
public static JsonElement GetFirstJsonElement(this JsonElement jsonElement, IEnumerable<string> paths)
56+
{
57+
if (jsonElement.ValueKind is JsonValueKind.Null || jsonElement.ValueKind is JsonValueKind.Undefined)
58+
{
59+
return default(JsonElement);
60+
}
61+
62+
var element = default(JsonElement);
63+
64+
foreach (var path in paths)
65+
{
66+
element = jsonElement.GetJsonElement(path);
67+
68+
if (element.ValueKind is JsonValueKind.Null || element.ValueKind is JsonValueKind.Undefined)
69+
{
70+
continue;
71+
}
72+
73+
break;
74+
}
75+
76+
return element;
77+
}
78+
4279
public static string GetJsonElementValue(this JsonElement jsonElement) => jsonElement.ValueKind != JsonValueKind.Null &&
4380
jsonElement.ValueKind != JsonValueKind.Undefined
4481
? jsonElement.ToString()

0 commit comments

Comments
 (0)