2024-10-09 12:08:16 -04:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2025-01-19 08:22:00 -05:00
|
|
|
"iter"
|
2024-10-09 12:08:16 -04:00
|
|
|
|
|
|
|
"github.com/tidwall/gjson"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
ErrGjsonNotFound = errors.New("specified path does not exist")
|
|
|
|
ErrGjsonWrongType = errors.New("wrong type")
|
|
|
|
)
|
|
|
|
|
2025-01-19 08:22:00 -05:00
|
|
|
var emptyIterator = func(yield func(string, string) bool) {}
|
|
|
|
|
2024-10-09 12:08:16 -04:00
|
|
|
func GjsonGet(json []byte, path string) (gjson.Result, error) {
|
|
|
|
result := gjson.GetBytes(json, path)
|
|
|
|
if !result.Exists() {
|
|
|
|
return result, ErrGjsonNotFound
|
|
|
|
}
|
|
|
|
|
|
|
|
return result, nil
|
|
|
|
}
|
|
|
|
|
2025-01-19 08:22:00 -05:00
|
|
|
func GjsonIter(json string) (iter.Seq2[string, string], error) {
|
|
|
|
if json == "" {
|
|
|
|
return emptyIterator, nil
|
2024-10-17 09:03:03 -04:00
|
|
|
}
|
|
|
|
|
2025-01-19 08:22:00 -05:00
|
|
|
result := gjson.Parse(json)
|
2024-10-09 12:08:16 -04:00
|
|
|
if !result.IsObject() {
|
|
|
|
return nil, ErrGjsonWrongType
|
|
|
|
}
|
|
|
|
|
2025-01-19 08:22:00 -05:00
|
|
|
return func(yield func(string, string) bool) {
|
|
|
|
result.ForEach(func(k, v gjson.Result) bool {
|
|
|
|
return yield(k.String(), v.String())
|
|
|
|
})
|
|
|
|
}, nil
|
2024-10-09 12:08:16 -04:00
|
|
|
}
|