如何在 Go 中迭代 []interface{}

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

我正在努力获取以下接口的键和值,这是JSON对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) 结果:[]interface{}.

我用它来遍历数组:

s := reflect.ValueOf(result)
for i := 0; i < s.Len(); i++ {
  singleVertex := s.Index(i).Elem() // What to do here?
}

但我遇到了以下错误:

reflect.Value.Interface: cannot return value obtained from unexported field or method

如果您知道那是您的数据结构,则根本没有理由使用反射。只需使用类型断言:

for key, value := range result.([]interface{})[0].([]interface{})[0].(map[string]interface{}) {
    // key == id, label, properties, etc
}

要获取接口的基础值,请使用类型断言。详细了解 Type assertion 及其工作原理。

package main

import (
    "fmt"
)

func main() {
     res, err := g.Execute( // Sends a query to Gremlin Server with bindings
           "g.V(x)",
            map[string]string{"x": "1234"},
            map[string]string{},
     )
     if err != nil {
          fmt.Println(err)
          return
     }
     fetchValue(res)
}

func fetchValue(value interface{}) {
    switch value.(type) {
    case string:
        fmt.Printf("%v is an interface \n ", value)
    case bool:
        fmt.Printf("%v is bool \n ", value)
    case float64:
        fmt.Printf("%v is float64 \n ", value)
    case []interface{}:
        fmt.Printf("%v is a slice of interface \n ", value)
        for _, v := range value.([]interface{}) { // use type assertion to loop over []interface{}
            fetchValue(v)
        }
    case map[string]interface{}:
        fmt.Printf("%v is a map \n ", value)
        for _, v := range value.(map[string]interface{}) { // use type assertion to loop over map[string]interface{}
            fetchValue(v)
        }
    default:
        fmt.Printf("%v is unknown \n ", value)
    }
}