Created
August 18, 2014 16:18
-
-
Save andreagrandi/876578acf03263fc7a03 to your computer and use it in GitHub Desktop.
Example of Unmarshal (from JSON to struct) in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
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
"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.