Fix up the recursive descent

Again I guess?
This commit is contained in:
2025-03-25 15:17:55 +01:00
parent d904f8ec13
commit 08d5d707d0
2 changed files with 31 additions and 5 deletions

View File

@@ -96,6 +96,32 @@ func readIndex(path string, start int) (string, int) {
return path[start:i], i return path[start:i], i
} }
func Get(data interface{}, path string) []interface{} {
steps, err := ParseJSONPath(path)
if err != nil {
log.Println("Error parsing JSONPath:", err)
return nil
}
return EvaluateJSONPath(data, steps)
}
func Set(data interface{}, path string, value interface{}) {
steps, err := ParseJSONPath(path)
if err != nil {
log.Println("Error parsing JSONPath:", err)
return
}
node := EvaluateJSONPath(data, steps)
if len(node) == 0 {
log.Println("No node found for path:", path)
return
}
if len(node) > 1 {
log.Println("Multiple nodes found for path:", path)
return
}
node[0] = value
}
func EvaluateJSONPath(data interface{}, steps []JSONStep) []interface{} { func EvaluateJSONPath(data interface{}, steps []JSONStep) []interface{} {
current := []interface{}{data} current := []interface{}{data}

View File

@@ -5,7 +5,7 @@ import (
"testing" "testing"
) )
var testData = map[string]interface{}{ var testData = map[string]interface{}{
"store": map[string]interface{}{ "store": map[string]interface{}{
"book": []interface{}{ "book": []interface{}{
map[string]interface{}{ map[string]interface{}{
@@ -70,7 +70,7 @@ func TestParser(t *testing.T) {
wantErr: true, wantErr: true,
}, },
{ {
path: "$.store.book[abc]", path: "$.store.book[abc]",
wantErr: true, wantErr: true,
}, },
} }
@@ -125,7 +125,7 @@ func TestEvaluator(t *testing.T) {
name: "wildcard_recursive", name: "wildcard_recursive",
path: "$..*", path: "$..*",
expected: []interface{}{ expected: []interface{}{
testData["store"], // Root element // testData["store"], // Root element
// Store children // Store children
testData["store"].(map[string]interface{})["book"], testData["store"].(map[string]interface{})["book"],
testData["store"].(map[string]interface{})["bicycle"], testData["store"].(map[string]interface{})["bicycle"],
@@ -164,7 +164,7 @@ func TestEvaluator(t *testing.T) {
} }
result := EvaluateJSONPath(testData, steps) result := EvaluateJSONPath(testData, steps)
// Special handling for wildcard recursive test // Special handling for wildcard recursive test
if tt.name == "wildcard_recursive" { if tt.name == "wildcard_recursive" {
if len(result) != len(tt.expected) { if len(result) != len(tt.expected) {
@@ -221,4 +221,4 @@ func TestEdgeCases(t *testing.T) {
t.Errorf("Expected 'answer', got %v", result) t.Errorf("Expected 'answer', got %v", result)
} }
}) })
} }