json - 使用 Go 获取 JSON 数组中的特定键

标签 json go

我花了很多时间解析 JSON 字符串,最后登陆了 https://github.com/bitly/go-simplejson .它看起来很有前途,但它仍然为我提供以下 JSON 数组的空结果:

{
 "data": {
  "translations": [
   {
    "translatedText": "Googlebot: Deutsch, um die Luft-Speed-Geschwindigkeit einer unbeladenen Schwalbe?"
   }
  ]
 }
}

我只想通过指定 key 来访问 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 始终为空白 :( 不胜感激。

最佳答案

您遇到的问题是函数 Get 不会递归搜索结构;它只会查找当前级别的 key 。

您可以做的是创建一个递归函数来搜索结构并在找到后返回值。下面是一个使用标准包 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")
    }

}

结果:

Googlebot: Deutsch, um die Luft-Speed-Geschwindigkeit einer unbeladenen Schwalbe?

Playground : http://play.golang.org/p/OkLQbbId0t

关于json - 使用 Go 获取 JSON 数组中的特定键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22675541/

相关文章:

java - 使用 JSON 进行 Spring Security 错误处理

java - 传递到 JSONObject 类后数据丢失

go - 为 big.Int 创建了类型别名 - 但我无法使用其指针接收器设置它?

go - 缓冲测试输出

Golang - 内部结构如何实现?

c - C 中的 JSON 序列化

javascript - 语法错误: Unexpected token v in JSON at position 2

java - JSON 对象属性名可以是整数吗?

Go 例子和成语

go - 尝试从永远不会在goroutine中接收数据但在主func中接收数据的 channel 读取时,为什么没有死锁