I'm struggling to get the keys and values of the following interface, which is the result of JSON marshaling the result returned by Execute
as demonstrated in this example:
[
[
{
"id": 36,
"label": "TestThing",
"properties": {
"schema__testBoolean": [
{
"id": 40,
"value": true
}
],
"schema__testInt": [
{
"id": 39,
"value": 1
}
],
"schema__testNumber": [
{
"id": 38,
"value": 1.0879834
}
],
"schema__testString": [
{
"id": 37,
"value": "foobar"
}
],
"uuid": [
{
"id": 41,
"value": "7f14bf92-341f-408b-be00-5a0a430852ee"
}
]
},
"type": "vertex"
}
]
]
A reflect.TypeOf(result)
results in: []interface{}
.
I've used this to loop over the array:
s := reflect.ValueOf(result)
for i := 0; i < s.Len(); i++ {
singleVertex := s.Index(i).Elem() // What to do here?
}
But I'm getting stuck with errors like:
reflect.Value.Interface: cannot return value obtained from unexported field or method
interface{} means you can put value of any type, including your own custom type. All types in Go satisfy an empty interface ( interface{} is an empty interface). In your example, Msg field can have value of any type.
To implement an interface in Go, you need to implement all the methods declared in the interface. Go Interfaces are implemented implicitly. Unlike Java, you don't need to explicitly specify using the implements keyword.
Since the interface is a type just like a struct, we can create a variable of its type. In the above case, we can create a variable s of type interface Shape .
If you know that's your data structure, there's no reason to use reflection at all. Just use a type assertion:
for key, value := range result.([]interface{})[0].([]interface{})[0].(map[string]interface{}) {
// key == id, label, properties, etc
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With