42. Go - JSON
Marshalling (Turning struct types into JSON format:
Code Example:
// marshall function takes anything and returns a slice of bytes
package main
import (
"encoding/json"
"fmt"
"os"
)
type serverInfo struct {
ID int
Name string
IsNew bool
Members []string
}
func main() {
serverOne := serverInfo{
ID: 0,
Name: "Crimson",
IsNew: false,
Members: []string{"Bob", "Ada"},
}
marshall, err := json.Marshal(serverOne)
if err != nil {
fmt.Println(err)
}
fmt.Println(marshall) // not correct format print
os.Stdout.Write(marshall) // write output
}
Un-Marshalling (Decoding a JSON format, which is a array of bytes for GO.
// unmarshall function takes a slice of byte and interface and returns an error. Takes decoded JSON and stores it at address given by interface.
Code Example:
package main
import (
"encoding/json"
"fmt"
"os"
)
type serverInfo struct {
ID int
Name string
IsNew bool
Members []string
}
func main() {
serverOne := serverInfo{
ID: 0,
Name: "Crimson",
IsNew: false,
Members: []string{"Bob", "Ada"},
}
testTable := []serverInfo{serverOne}
marshaled, err := json.Marshal(testTable)
if err != nil {
fmt.Println(err)
}
fmt.Println(marshaled) // not correct format print
os.Stdout.Write(marshaled) // write output
fmt.Println("B")
var servers []serverInfo
unmarshaled := json.Unmarshal(marshaled, &servers)
if unmarshaled != nil {
fmt.Println(err)
}
fmt.Println(servers, "A")
}
Unmarshalling JSON by creating a type struct with JSON tags:
// need to define the structure of the JSON with a struct and JSON tags, struct vars must match tags
Code Example:
package main
import (
"encoding/json"
"fmt"
)
type serverInfo struct {
ID int `json:"ID"`
Name string `json:"Name"`
IsNew bool `json:"IsNew"`
Members []string `json:"Members"`
}
func main() {
jsonString := `[{"ID":0,"Name":"Crimson","IsNew":false,"Members":["Bob","Ada"]}]`
jsonBytes := []byte(jsonString)
var serverList []serverInfo
err := json.Unmarshal(jsonBytes, &serverList)
if err != nil {
fmt.Println(err)
}
fmt.Println(serverList)
fmt.Println(serverList[0], "index one")
fmt.Println(serverList[0].ID, "Index 1: ID")
fmt.Println(serverList[0].Name, "Index 1: Name")
fmt.Println(serverList[0].IsNew, "Index 1: IsNew")
fmt.Println(serverList[0].Members, "Index 1: Members")
fmt.Println(serverList[0].Members[1], "Index 1: Members[1]")
}
Comments
Post a Comment