go json - kimschles/schlesinger-knowledge GitHub Wiki
Go and JSON
- The encoding/json go package lets you encode and decode JSON objects.
- The Marshal function lets you encode (convert a struct) to JSON data.
- The Unmarshal function accepts JSON and decodes it into a struct(?) or other go data type.
The examples below are from https://blog.golang.org/json
Marshal Example
package main
import (
"encoding/json"
"fmt"
)
// Message comment
type Message struct {
Name string
Body string
Time int64
}
// Marshal example
func main() {
m := Message{"Kim", "Hello", 1294706395881547000}
jsonMessage, err := json.Marshal(m)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(jsonMessage))
}
Unmarshal Example
package main
import (
"encoding/json"
"fmt"
)
// Message comment
type Message struct {
Name string
Food string
}
// Unmarshal example
func main() {
b := []byte(`{"Name":"Bob","Food":"Pickle"}`)
var m Message
if err := json.Unmarshal(b, &m); err != nil {
fmt.Println(err)
}
fmt.Println(m)
}