Accessing custom fragments from child-additions #106
-
|
Hi, I'm having a Managed Object with two child-additions in my tenant. Both child-additions are having the same custom fragment (in this example package main
import (
"context"
"fmt"
"github.com/reubenmiller/go-c8y/pkg/c8y"
)
func main() {
client := c8y.NewClientFromEnvironment(nil, false)
mor, _, _ := client.Inventory.GetChildAdditions(context.Background(), "9261202",
&c8y.ManagedObjectOptions{
Query: "type eq myTest",
})
for _, mo := range mor.References {
fmt.Println(mo.ManagedObject.ID)
helloValue := mo.ManagedObject.Item.Get("hello")
fmt.Println(helloValue)
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
This is one of the trickier parts that I haven't been able to solve nicely. Basically, when the response is an array of objects, the For most collections, the sdk adds a generic But in the future, if the returned object does not contain the information that you want, you can always fallback to using the response object (typically the second argument returned from any api calls), so you could of rewritten your example with (but the latest v0.28.0 release includes the func main() {
client := c8y.NewClientFromEnvironment(nil, false)
_, resp, err := client.Inventory.GetChildAdditions(context.Background(), "25636204",
&c8y.ManagedObjectOptions{
Query: "type eq myTest",
})
if err != nil {
panic("request failed")
}
for _, mor := range resp.JSON("references").Array() {
fmt.Printf("managedObject.id: %s\n", mor.Get("managedObject.id").String())
if helloValue := mor.Get("managedObject.hello"); helloValue.Exists() {
fmt.Printf("managedObject.hello: %s\n", helloValue)
} else {
fmt.Printf("managedObject.hello: <unset>\n")
}
}
} |
Beta Was this translation helpful? Give feedback.
This is one of the trickier parts that I haven't been able to solve nicely. Basically, when the response is an array of objects, the
.Itemproperty of an item in the array (e.g. the.ManagedObjectin this case) does not have the raw JSON related to that items json array...so you can't access custom fields from it.For most collections, the sdk adds a generic
.Itemswhich is an array of gjson objects, where gjson can be used to access any field using dot notation. Though the problem you ran into was that the managed object references structs, didn't have the.Itemsset, however I've just pushed a new version, v0.28.0 to fix this, and added a client example where I just took your example ab…