你的問題是,該功能Get
不會遞歸搜索結構;它只會查找當前級別的密鑰。
您可以做的是創建一個遞歸函數,用於搜索e結構並在找到它時返回該值。下面是一個使用一個工作示例標準包encoding/json
:
package main
import (
"encoding/json"
"fmt"
)
// SearchNested searches a nested structure consisting of map[string]interface{}
// and []interface{} looking for a map with a specific key name.
// If found SearchNested returns the value associated with that key, true
// If the key is not found SearchNested returns nil, false
func SearchNested(obj interface{}, key string) (interface{}, bool) {
switch t := obj.(type) {
case map[string]interface{}:
if v, ok := t[key]; ok {
return v, ok
}
for _, v := range t {
if result, ok := SearchNested(v, key); ok {
return result, ok
}
}
case []interface{}:
for _, v := range t {
if result, ok := SearchNested(v, key); ok {
return result, ok
}
}
}
// key not found
return nil, false
}
func main() {
jsonData := []byte(`{
"data": {
"translations": [
{
"translatedText": "Googlebot: Deutsch, um die Luft-Speed-Geschwindigkeit einer unbeladenen Schwalbe?"
}
]
}
}`)
// First we unmarshal into a generic interface{}
var j interface{}
err := json.Unmarshal(jsonData, &j)
if err != nil {
panic(err)
}
if v, ok := SearchNested(j, "translatedText"); ok {
fmt.Printf("%+v\n", v)
} else {
fmt.Println("Key not found")
}
}
結果:
谷歌機器人:德語,嗯死拉夫特高速-Geschwindigkeit einer unbeladenen施瓦爾貝?
遊樂場:http://play.golang.org/p/OkLQbbId0t
令人驚歎。謝謝。 – Etienne
@Etienne:歡迎光臨!請注意,如果結構中有多個相同鍵名的實例,它將返回它找到的第一個鍵。如果你使用嵌套的JSON對象而不是數組(你似乎這樣做),那麼返回值將是任意的。 Happy Go編碼! – ANisus