在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?

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

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