我有一段时间解析JSON字符串,最后登陆https://github.com/bitly/go-simplejson.它看起来很有前途,但它仍然给我一个空的结果,以下JSON数组:
{
"data": {
"translations": [
{
"translatedText": "Googlebot: Deutsch, um die Luft-Speed-Geschwindigkeit einer unbeladenen Schwalbe?"
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
我想translatedText通过仅指定密钥来实现.原因是我的JSON结构不可预测,所以我想定位任何JSON数组,但指定一个键而不知道JSON数组的完整结构.
这是我使用的代码片段,其中content包含JSON字节数组:
f, err := js.NewJson(content)
if err != nil {
log.Println(err)
}
t := f.Get("translatedText").MustString()
log.Println(t)
Run Code Online (Sandbox Code Playgroud)
t 总是空白:(不胜感激任何指针.
你遇到的问题是该函数Get不会递归搜索结构; 它只会查找当前级别的密钥.
你可以做的是创建一个递归函数,搜索结构并在找到它后返回值.以下是使用标准包的工作示例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")
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
Googlebot:Deutsch,嗯死Luft-Speed-Geschwindigkeit einer unbeladenen Schwalbe?
游乐场: http ://play.golang.org/p/OkLQbbId0t