Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over an []interface{} in Go

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

like image 276
Bob van Luijt Avatar asked Jul 04 '18 11:07

Bob van Luijt


People also ask

What is [] interface {} Golang?

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.

How do you implement an interface in Go?

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.

CAN interface have variables in Go?

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 .


1 Answers

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
}
like image 145
Flimzy Avatar answered Sep 23 '22 01:09

Flimzy