Update function for iterating over object entries

This commit is contained in:
Svilen Markov
2025-07-19 16:43:40 +01:00
parent d39e114efe
commit 38f1243b41
2 changed files with 9 additions and 19 deletions

View File

@ -232,8 +232,8 @@ JSON response:
To loop through each property of the object, you would use the following: To loop through each property of the object, you would use the following:
```html ```html
{{ range .JSON.Object "user" }} {{ range $key, $value := .JSON.Entries "user" }}
<div>{{ .Key }}: {{ .Value.String "" }}</div> <div>{{ $key }}: {{ $value.String "" }}</div>
{{ end }} {{ end }}
``` ```
@ -245,7 +245,7 @@ Output:
<div>active: true</div> <div>active: true</div>
``` ```
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.
<hr> <hr>

View File

@ -8,6 +8,7 @@ import (
"fmt" "fmt"
"html/template" "html/template"
"io" "io"
"iter"
"log/slog" "log/slog"
"math" "math"
"net/http" "net/http"
@ -420,19 +421,7 @@ func (r *decoratedGJSONResult) Get(key string) *decoratedGJSONResult {
return &decoratedGJSONResult{r.Result.Get(key)} return &decoratedGJSONResult{r.Result.Get(key)}
} }
func gjsonResultObjectToPropertyArray(obj gjson.Result) []ObjectProperty { func (r *decoratedGJSONResult) Entries(key string) iter.Seq2[string, *decoratedGJSONResult] {
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 {
var obj gjson.Result var obj gjson.Result
if key == "" { if key == "" {
obj = r.Result obj = r.Result
@ -440,10 +429,11 @@ func (r *decoratedGJSONResult) Object(key string) []ObjectProperty {
obj = r.Result.Get(key) obj = r.Result.Get(key)
} }
if !obj.IsObject() { return func(yield func(string, *decoratedGJSONResult) bool) {
return []ObjectProperty{} 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 { func customAPIDoMathOp[T int | float64](a, b T, op string) T {