dongshao2967 2016-06-07 13:55
浏览 73
已采纳

手动读取JSON值

In Go I usually unmarshal my JSON into a struct and read values from the struct.. it works very well.

This time around I am only concerned with a certain element of a JSON object and because the overall JSON object is very large, I don't want to have to create a struct.

Is there a way in Go so that I can lookup values in the JSON object using keys or iterate arrays as per usual.

Considering the following JSON how could I pull out the title field only.

{
  "title": "Found a bug",
  "body": "I'm having a problem with this.",
  "assignee": "octocat",
  "milestone": 1,
  "labels": [
    "bug"
  ]
}
  • 写回答

5条回答 默认 最新

  • douzhi4991 2016-06-07 15:50
    关注

    To extend Darigaaz's answer, you can also use an anonymous struct declared within the parsing function. This avoids having to have package-level type declarations litter the code for single-use cases.

    https://play.golang.org/p/MkOo1KNVbs

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    func main() {
        test := `{
            "title": "Found a bug",
            "body": "I'm having a problem with this.",
            "assignee": "octocat",
            "milestone": 1,
            "labels": [
              "bug"
            ]
        }`
    
        var s struct {
            Title string `json:"title"`
        }
        json.Unmarshal([]byte(test), &s)
    
        fmt.Printf("%#v", s)
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料