-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
82 additions
and
46 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
using System.Text.Json; | ||
|
||
namespace Hyperbee.Json; | ||
|
||
public class JsonPathBuilder | ||
{ | ||
private readonly JsonElement _rootElement; | ||
|
||
public JsonPathBuilder( JsonDocument rootDocument ) | ||
{ | ||
_rootElement = rootDocument.RootElement; | ||
} | ||
|
||
public JsonPathBuilder( JsonElement rootElement ) | ||
{ | ||
_rootElement = rootElement; | ||
} | ||
|
||
public string GetPath( JsonElement targetElement ) | ||
{ | ||
var comparer = new JsonElementPositionComparer(); | ||
|
||
var stack = new Stack<(JsonElement element, string path)>( 4 ); | ||
stack.Push( (_rootElement, string.Empty) ); | ||
|
||
while ( stack.Count > 0 ) | ||
{ | ||
var (currentElement, currentPath) = stack.Pop(); | ||
|
||
if ( comparer.Equals( currentElement, targetElement ) ) | ||
return currentPath; | ||
|
||
switch ( currentElement.ValueKind ) | ||
{ | ||
case JsonValueKind.Object: | ||
foreach ( JsonProperty property in currentElement.EnumerateObject() ) | ||
{ | ||
var newPath = string.IsNullOrEmpty( currentPath ) ? property.Name : $"{currentPath}.{property.Name}"; | ||
stack.Push( (property.Value, newPath) ); | ||
} | ||
|
||
break; | ||
|
||
case JsonValueKind.Array: | ||
var index = 0; | ||
foreach ( JsonElement element in currentElement.EnumerateArray() ) | ||
{ | ||
var newPath = $"{currentPath}[{index}]"; | ||
stack.Push( (element, newPath) ); | ||
index++; | ||
} | ||
|
||
break; | ||
} | ||
} | ||
|
||
return null; // Target element not found in the JSON document | ||
} | ||
} |