-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
b1c2fb0
commit 62e96bc
Showing
1 changed file
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -605,3 +605,33 @@ func main() { | |
} | ||
} | ||
``` | ||
### Loop through an object or array. | ||
The `Foreach` method enables efficient iteration over objects or arrays. For objects, both the key and value are provided to the callback function, while for arrays, only the value is passed. The iteration can be halted by returning `false` from the callback. | ||
eg. | ||
```go | ||
package main | ||
import ( | ||
"fmt" | ||
"github.com/sivaosorg/fj" | ||
) | ||
var json []byte = []byte(`{"user":{"id":"12345","name":{"firstName":"John","lastName":"Doe"},"email":"[email protected]","phone":"+1-555-555-5555","address":{"street":"123 Main St","city":"Anytown","state":"CA","postalCode":"12345","country":"USA"},"roles":[{"roleId":"1","roleName":"Admin","permissions":[{"permissionId":"101","permissionName":"View Reports","allowedActions":["view","download"]},{"permissionId":"102","permissionName":"Manage Users","allowedActions":["create","update","delete"]}]},{"roleId":"2","roleName":"Editor","permissions":[{"permissionId":"201","permissionName":"Edit Content","allowedActions":["create","edit","publish"]},{"permissionId":"202","permissionName":"View Analytics","allowedActions":["view"]}]}],"status":"active","createdAt":"2025-01-01T10:00:00Z","lastLogin":"2025-01-12T15:30:00Z"}}`) | ||
func main() { | ||
ctx := fj.GetBytes(json, "user.roles.#.permissions") | ||
ctx.Foreach(func(key, value fj.Context) bool { | ||
fmt.Println(value.String()) | ||
return true | ||
}) | ||
} | ||
// output: | ||
// [{"permissionId":"101","permissionName":"View Reports","allowedActions":["view","download"]},{"permissionId":"102","permissionName":"Manage Users","allowedActions":["create","update","delete"]}] | ||
// [{"permissionId":"201","permissionName":"Edit Content","allowedActions":["create","edit","publish"]},{"permissionId":"202","permissionName":"View Analytics","allowedActions":["view"]}] | ||
``` |