Merge pull request #746 from ralphocdol/custom-api-object-range

Added Object helper for custom-api
pull/697/head
Svilen Markov 2025-07-19 18:52:50 +07:00 committed by GitHub
commit 24eff13ef2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 49 additions and 0 deletions

@ -219,6 +219,38 @@ Output:
JSON response: JSON response:
```json
{
"user": {
"id": 42,
"name": "Alice",
"active": true
}
}
```
To loop through each property of the object, you would use the following:
```html
{{ range $key, $value := .JSON.Entries "user" }}
<div>{{ $key }}: {{ $value.String "" }}</div>
{{ end }}
```
Output:
```html
<div>id: 42</div>
<div>name: Alice</div>
<div>active: true</div>
```
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>
JSON response:
```json ```json
{ {
"price": 100, "price": 100,
@ -414,6 +446,7 @@ The following functions are available on the `JSON` object:
- `Bool(key string) bool`: Returns the value of the key as a boolean. - `Bool(key string) bool`: Returns the value of the key as a boolean.
- `Array(key string) []JSON`: Returns the value of the key as an array of `JSON` objects. - `Array(key string) []JSON`: Returns the value of the key as an array of `JSON` objects.
- `Exists(key string) bool`: Returns true if the key exists in the JSON object. - `Exists(key string) bool`: Returns true if the key exists in the JSON object.
- `Entries(key string)`: Returns an iterator that allows you to loop through each property of the object. Example: `{{ range $key, $value := .JSON.Entries "user" }}`. This will yield pairs of key and value, where `$key` is a string and `$value` is a `JSON` object.
The following functions are available on the `Options` object: The following functions are available on the `Options` object:

@ -8,6 +8,7 @@ import (
"fmt" "fmt"
"html/template" "html/template"
"io" "io"
"iter"
"log/slog" "log/slog"
"math" "math"
"net/http" "net/http"
@ -415,6 +416,21 @@ func (r *decoratedGJSONResult) Get(key string) *decoratedGJSONResult {
return &decoratedGJSONResult{r.Result.Get(key)} return &decoratedGJSONResult{r.Result.Get(key)}
} }
func (r *decoratedGJSONResult) Entries(key string) iter.Seq2[string, *decoratedGJSONResult] {
var obj gjson.Result
if key == "" {
obj = r.Result
} else {
obj = r.Result.Get(key)
}
return func(yield func(string, *decoratedGJSONResult) bool) {
obj.ForEach(func(k, v gjson.Result) bool {
return yield(k.String(), &decoratedGJSONResult{v})
})
}
}
func customAPIDoMathOp[T int | float64](a, b T, op string) T { func customAPIDoMathOp[T int | float64](a, b T, op string) T {
switch op { switch op {
case "add": case "add":