2014-10-06 63 views
1

我有一個隨機的JSON(我不會提前知道架構),因此我編組爲map[string]interface{}。 我還有一個字符串,表示我想返回的字段值,類似於"SomeRootKey.NestValue.AnotherNestValue"在Go地圖中訪問嵌套值

我希望能夠返回該值。有沒有一種簡單的方法來訪問該值,而不需要執行一些遞歸技巧?

回答

1

沒有遞歸?是的,使用循環,但沒有沒有不可思議的方式來做到這一點。

func getKey(m interface{}, key string) (string, bool) { 
L: 
    for _, k := range strings.Split(key, ".") { 
     var v interface{} 
     switch m := m.(type) { 
     case map[string]interface{}: 
      v = m[k] 
     case []interface{}: 
      idx, err := strconv.Atoi(k) 
      if err != nil || idx > len(m) { 
       break L 
      } 
      v = m[idx] 
     default: 
      break L 
     } 
     switch v := v.(type) { 
     case map[string]interface{}: 
      m = v 
     case []interface{}: 
      m = v 
     case string: 
      return v, true 
     default: 
      break L 
     } 
    } 
    return "", false 
} 

使用JSON,如:

{ 
    "SomeRootKey": { 
     "NestValue": {"AnotherNestValue": "object value"}, 
     "Array": [{"AnotherNestValue": "array value"}] 
    } 
} 

您可以使用:

fmt.Println(getKey(m, "SomeRootKey.NestValue.AnotherNestValue")) 
fmt.Println(getKey(m, "SomeRootKey.Array.0.AnotherNestValue")) 

playground

+0

但將它這不會使用數組?像「a.b [0] .val」 – K2xL 2014-10-09 14:01:37

+0

@ K2xL我更新了代碼。 – OneOfOne 2014-10-09 14:16:09