Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marshall and UnMarshall JSON Content in GoLang

Tags:

json

go

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.

like image 419
Rahul Avatar asked Nov 22 '13 21:11

Rahul


People also ask

What is JSON marshal and Unmarshal in Golang?

In Golang, struct data is converted into JSON and JSON data to string with Marshal() and Unmarshal() method. The methods returned data in byte format and we need to change returned data into JSON or String. In our previous tutorial, we have explained about Parsing JSON Data in Golang.

What does JSON Marshal do in Golang?

Marshaling: Converting Go objects to JSON We can use the Marshal function to convert Go objects to JSON. The Marshal function comes with the following syntax. It accepts an empty interface. In other words, you can provide any Go data type to the function — an integer, float, string, struct, map, etc.

How do I read JSON data in Golang?

Golang provides multiple APIs to work with JSON including to and from built-in and custom data types using the encoding/json package. To parse JSON, we use the Unmarshal() function in package encoding/json to unpack or decode the data from JSON to a struct.

What is marshalling and unmarshalling JSON?

Generally, encoding/decoding JSON refers to the process of actually reading/writing the character data to a string or binary form. Marshaling/Unmarshaling refers to the process of mapping JSON types from and to Go data types and primitives.


1 Answers

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"`
}
like image 66
fabrizioM Avatar answered Sep 23 '22 05:09

fabrizioM