Varun Gupta Varun Gupta - 12 days ago 5
JSON Question

Parsing json file in golang

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?

Answer

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\n", err.Error())
    }
    fmt.Printf("%+v\n", j.Text[0].Sha)
}
Comments