英文:
Getting to a specific key in JSON array using Go
问题
我在解析JSON字符串方面遇到了很多困难,最终找到了https://github.com/bitly/go-simplejson这个库。它看起来非常有前途,但对于以下JSON数组,它仍然给我返回一个空结果:
{
"data": {
"translations": [
{
"translatedText": "Googlebot: Deutsch, um die Luft-Speed-Geschwindigkeit einer unbeladenen Schwalbe?"
}
]
}
}
我想通过只指定键名来获取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)
t
始终为空 希望能得到一些指导。
英文:
I've had a heck of a time parsing JSON strings and finally landed on https://github.com/bitly/go-simplejson. It looks really promising but it's still giving me an empty result for the following JSON array:
{
"data": {
"translations": [
{
"translatedText": "Googlebot: Deutsch, um die Luft-Speed-Geschwindigkeit einer unbeladenen Schwalbe?"
}
]
}
}
I want to get to translatedText
by only specifying the key. The reason for this is my JSON structure won't be predictable and so I'd like to target any JSON array but specifying a key without knowing the full structure of the JSON array.
This is the snippet of code I use where content
contains the JSON byte array:
f, err := js.NewJson(content)
if err != nil {
log.Println(err)
}
t := f.Get("translatedText").MustString()
log.Println(t)
t
is always blank Would appreciate any pointers.
答案1
得分: 6
你遇到的问题是Get
函数不会递归搜索结构体;它只会在当前层级查找键。
你可以创建一个递归函数来搜索结构体,并在找到值后返回。下面是使用标准包encoding/json
的一个工作示例:
package main
import (
"encoding/json"
"fmt"
)
// SearchNested在由map[string]interface{}和[]interface{}组成的嵌套结构中搜索具有特定键名的map。
// 如果找到,则SearchNested返回与该键关联的值和true。
// 如果未找到键,则SearchNested返回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
}
}
}
// 未找到键
return nil, false
}
func main() {
jsonData := []byte(`{
"data": {
"translations": [
{
"translatedText": "Googlebot: Deutsch, um die Luft-Speed-Geschwindigkeit einer unbeladenen Schwalbe?"
}
]
}
}`)
// 首先,我们将其解组为一个通用的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("未找到键")
}
}
结果:
Googlebot: Deutsch, um die Luft-Speed-Geschwindigkeit einer unbeladenen Schwalbe?
Playground: http://play.golang.org/p/OkLQbbId0t
英文:
The problem you have is that the function Get
does not recursively search through the structure; it only does a look up for the key the at the current level.
What you can do is to create a recursive function that searches the structure and returns the value once it is found. Below is a working example using the standard package 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")
}
}
Result:
>Googlebot: Deutsch, um die Luft-Speed-Geschwindigkeit einer unbeladenen Schwalbe?
Playground: http://play.golang.org/p/OkLQbbId0t
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论