douqian5553
2016-11-21 17:35
浏览 21
已采纳

在golang中解析json文件[关闭]

I have a json structure like this

{  
"some text":[  
  {  
     "sha":"1234567",
     "message":"hello world",
     "author":"varung",
     "timestamp":1479445228
  }
]
}

I need to access the value of sha, using golang. How can I do it?

图片转代码服务由CSDN问答提供 功能建议

我有这样的json结构

  {
  “ some text”:[
 {
“ sha”:“ 1234567”,
“ message”:“ hello world”,
“ author”:“ varung”,
“ timestamp”:1479445228 
}  
] 
} 
   
 
 

我需要使用golang访问sha的值。 我该怎么办?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doushuichong2589 2016-11-21 17:51
    已采纳

    You can use Go's encoding/json package quite easily. Here is a playground link to the code below.

    package main
    
    import (
        "encoding/json"
        "fmt"
        "log"
    )
    
    var a = `{  
    "sometext":[  
      {  
         "sha":"1234567",
         "message":"hello world",
         "author":"varung",
         "timestamp":1479445228
      }
    ]
    }`
    
    type Root struct {
        Text []*Object `json:"sometext"`
    }
    
    type Object struct {
        Sha       string `json:"sha"`
        Message   string `json:"message"`
        Author    string `json:"author"`
        Timestamp int    `json:"timestamp"`
    }
    
    func main() {
        var j Root
        err := json.Unmarshal([]byte(a), &j)
        if err != nil {
            log.Fatalf("error parsing JSON: %s
    ", err.Error())
        }
        fmt.Printf("%+v
    ", j.Text[0].Sha)
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongshan0202405 2016-11-21 17:52

    I don't know of any way other than unmarshaling the json.

    import (
            "time"
            "fmt"
            "encoding/json"
    )
    
    type MyObj struct {
      Sha string `json:"sha"`
      Message string `json:"message"`
      Author string `json:"author"`
      Timestamp time.Time `json:"timestamp"`
    }
    
    type MyObjs struct {
      Objs []MyObj `json:"some text"`
    } 
    
    func PrintSha(json []byte) {
      var myObjs MyObjs
      if err := json.Unmarshal(json, &myObjs); err != nil {
        panic(err)
      }
      myObj := myObjs[0]
      fmt.Println(myObj.sha)
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题