-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonFieldExtractor.cs
More file actions
45 lines (36 loc) · 1.36 KB
/
JsonFieldExtractor.cs
File metadata and controls
45 lines (36 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using System.Text.Json;
namespace TxFormFieldMapper;
internal static class JsonFieldExtractor
{
public static IReadOnlyList<string> GetFieldNames(string jsonPath)
{
using var stream = File.OpenRead(jsonPath);
using var document = JsonDocument.Parse(stream);
var names = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
CollectObjectPropertyNames(document.RootElement, parentPath: null, names);
return names.ToList();
}
private static void CollectObjectPropertyNames(JsonElement element, string? parentPath, ISet<string> names)
{
switch (element.ValueKind)
{
case JsonValueKind.Object:
foreach (var property in element.EnumerateObject())
{
var path = string.IsNullOrWhiteSpace(parentPath)
? property.Name
: $"{parentPath}.{property.Name}";
names.Add(path);
names.Add(property.Name);
CollectObjectPropertyNames(property.Value, path, names);
}
break;
case JsonValueKind.Array:
foreach (var item in element.EnumerateArray())
{
CollectObjectPropertyNames(item, parentPath, names);
}
break;
}
}
}