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条)

报告相同问题?

悬赏问题

  • ¥20 matlab计算中误差
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊