55 lines
932 B
Go
55 lines
932 B
Go
package cnf
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"strings"
|
|
)
|
|
|
|
type Json struct {
|
|
data interface{}
|
|
parsed bool
|
|
}
|
|
|
|
// Parse extract a reader as its JSON representation
|
|
func (d *Json) Parse(_reader io.Reader) error {
|
|
|
|
// 1. get json decoder
|
|
decoder := json.NewDecoder(_reader)
|
|
err := decoder.Decode(&d.data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
d.parsed = true
|
|
return nil
|
|
|
|
}
|
|
|
|
// Get returns the value of a dot-separated path, and if it exists
|
|
func (d *Json) Get(_path string) (string, bool) {
|
|
|
|
// 1. extract path
|
|
path := strings.Split(_path, ".")
|
|
|
|
// 2. Iterate over path / nested fields
|
|
current := d.data
|
|
for _, field := range path {
|
|
fmap, ok := current.(map[string]interface{})
|
|
if !ok { // incomplete path
|
|
return "", false
|
|
}
|
|
|
|
child, ok := fmap[field]
|
|
if !ok { // incomplete path
|
|
return "", false
|
|
}
|
|
|
|
current = child
|
|
}
|
|
|
|
// 3. Only return if string value
|
|
value, ok := current.(string)
|
|
return value, ok
|
|
}
|