你的问题是,该功能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