-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
52 lines (44 loc) · 1.46 KB
/
json.go
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
46
47
48
49
50
51
52
package resolver
import (
"encoding/json"
"fmt"
"os"
"strings"
)
// Resolves a value by loading a JSON file and extracting a nested key.
// The value after the prefix should be in the format "path/to/file.json//key1.key2.keyN"
// If no key is provided, returns the entire JSON file as a string.
// Example:
// "json:/config/app.json//server.host"
// would load app.json, parse it as JSON, and then return the value at server.host.
//
// Keys are navigated via dot notation.
// If no key is provided (no "//" present), returns the entire JSON file as string.
type JSONResolver struct{}
func (r *JSONResolver) Resolve(value string) (string, error) {
filePath, keyPath := splitFileAndKey(value)
filePath = os.ExpandEnv(filePath)
data, err := os.ReadFile(filePath)
if err != nil {
return "", fmt.Errorf("failed to read JSON file '%s': %w", filePath, err)
}
if keyPath == "" {
// Return whole file
return strings.TrimSpace(string(data)), nil
}
var content map[string]interface{}
if err := json.Unmarshal(data, &content); err != nil {
return "", fmt.Errorf("failed to parse JSON in '%s': %w", filePath, err)
}
val, err := navigateData(content, strings.Split(keyPath, "."))
if err != nil {
return "", fmt.Errorf("key path '%s' not found in JSON '%s': %w", keyPath, filePath, err)
}
strVal, ok := val.(string)
if !ok {
// If the value isn't a string, return its JSON representation
jData, _ := json.Marshal(val)
return string(jData), nil
}
return strVal, nil
}