Rahul
Rahul

Reputation: 11669

Marshall and UnMarshall JSON Content in GoLang

I have a sample json file which is structured like this

{
  "method":"brute_force",
  "bc":"select * from blah;",
  "gc":[
    "select sum(year) from blah;",
    "select count(*) from table;"
      ]
}

I am trying to write a go program which can read this file and operate of json content.

package main 
import (
    "fmt"
    "encoding/json"
    "io/ioutil"
    )


type Response2 struct {
    method string
    bc string
    gc []string
}

func main() {
    file,_ := ioutil.ReadFile("config.json")
    fmt.Printf("%s",string(file))

        res := &Response2{}


        json.Unmarshal([]byte(string(file)), &res)
        fmt.Println(res)

        fmt.Println(res.method)
        fmt.Println(res.gc)

}

res.method and res.gc dont print anything. I have no idea on whats going wrong.

Upvotes: 7

Views: 5444

Answers (1)

fabmilo
fabmilo

Reputation: 48330

type Response2 struct {
    method string
    bc string
    gc []string
}

The name of the fields Must be Uppercase otherwise the Json module can't access them (they are private to your module). You can use the json tag to specify a match between Field and name

type Response2 struct {
    Method string `json:"method"`
    Bc string `json:"bc"`
    Gc []string `json:"gc"`
}

Upvotes: 9

Related Questions