From 38f1243b4189db130fecf50b4f55007644ea66fc Mon Sep 17 00:00:00 2001 From: Svilen Markov <7613769+svilenmarkov@users.noreply.github.com> Date: Sat, 19 Jul 2025 16:43:40 +0100 Subject: [PATCH] Update function for iterating over object entries --- docs/custom-api.md | 6 +++--- internal/glance/widget-custom-api.go | 22 ++++++---------------- 2 files changed, 9 insertions(+), 19 deletions(-) diff --git a/docs/custom-api.md b/docs/custom-api.md index 7b0beae..6b8711a 100644 --- a/docs/custom-api.md +++ b/docs/custom-api.md @@ -232,8 +232,8 @@ JSON response: To loop through each property of the object, you would use the following: ```html -{{ range .JSON.Object "user" }} -
{{ .Key }}: {{ .Value.String "" }}
+{{ range $key, $value := .JSON.Entries "user" }} +
{{ $key }}: {{ $value.String "" }}
{{ end }} ``` @@ -245,7 +245,7 @@ Output:
active: true
``` -Each property in the object is exposed as a pair, with `.Key` giving the property name and `.Value` providing access to the value using the usual JSON methods. +Each property in the object is exposed as a pair, with `$key` being a string and `$value` providing access to the value using the usual JSON methods.
diff --git a/internal/glance/widget-custom-api.go b/internal/glance/widget-custom-api.go index 3ae1e4e..1a029db 100644 --- a/internal/glance/widget-custom-api.go +++ b/internal/glance/widget-custom-api.go @@ -8,6 +8,7 @@ import ( "fmt" "html/template" "io" + "iter" "log/slog" "math" "net/http" @@ -420,19 +421,7 @@ func (r *decoratedGJSONResult) Get(key string) *decoratedGJSONResult { return &decoratedGJSONResult{r.Result.Get(key)} } -func gjsonResultObjectToPropertyArray(obj gjson.Result) []ObjectProperty { - results := make([]ObjectProperty, 0) - obj.ForEach(func(k, v gjson.Result) bool { - results = append(results, ObjectProperty{ - Key: k.String(), - Value: decoratedGJSONResult{v}, - }) - return true - }) - return results -} - -func (r *decoratedGJSONResult) Object(key string) []ObjectProperty { +func (r *decoratedGJSONResult) Entries(key string) iter.Seq2[string, *decoratedGJSONResult] { var obj gjson.Result if key == "" { obj = r.Result @@ -440,10 +429,11 @@ func (r *decoratedGJSONResult) Object(key string) []ObjectProperty { obj = r.Result.Get(key) } - if !obj.IsObject() { - return []ObjectProperty{} + return func(yield func(string, *decoratedGJSONResult) bool) { + obj.ForEach(func(k, v gjson.Result) bool { + return yield(k.String(), &decoratedGJSONResult{v}) + }) } - return gjsonResultObjectToPropertyArray(obj) } func customAPIDoMathOp[T int | float64](a, b T, op string) T {