Skip to content

Instantly share code, notes, and snippets.

@andreagrandi
Created August 18, 2014 16:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreagrandi/876578acf03263fc7a03 to your computer and use it in GitHub Desktop.
Save andreagrandi/876578acf03263fc7a03 to your computer and use it in GitHub Desktop.
Example of Unmarshal (from JSON to struct) in Go
package main
import (
"fmt"
"encoding/json"
)
type Message struct {
Name string
Body string
Time int64
}
func main() {
json_test := []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000,"Test":"Test Value"}`)
var m Message
err := json.Unmarshal(json_test, &m)
if err != nil {
panic(err)
}
fmt.Print(m)
}
@andreagrandi
Copy link
Author

"Test" field is not included in Message struct, because in my example I wanted to show that it's possible to partially unmarshal a JSON string.

@harel
Copy link

harel commented Aug 19, 2014

Can also use:

type Message struct {
    Name string `json: "name"`
    Body string `json: "body"`
    Time int64 `json: "boogabooga"`
}

to unmarshal a json packet with more freeform key names:

{"name":"Alice","Body":"hello","boogabooga":1294706395881547000,"Test":"Test Value"}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment