marshal Go to JSON
👍 vi movie.go
👍 go run movie.go
[
{
"Title": "Casablanca",
"released": 1942,
"Actors": [
"Humphrey Bogart",
"Ingrid Bergman"
]
},
{
"Title": "Cool Hand Luke",
"released": 1967,
"color": true,
"Actors": [
"Paul Newman"
]
}
]
[{Casablanca} {Cool Hand Luke}]
👍 cat movie.go
package main
import (
"encoding/json"
"log"
"fmt"
)
type Movie struct {
Title string
Year int `json:"released"`
Color bool `json:"color,omitempty"`
Actors []string
}
var movies = []Movie{
{Title: "Casablanca", Year: 1942,
Color: false, Actors: []string{
"Humphrey Bogart",
"Ingrid Bergman"}},
{Title: "Cool Hand Luke", Year: 1967,
Color: true, Actors: []string{
"Paul Newman"}},
}
func main() {
data, err := json.MarshalIndent(
movies, "", " ")
if err != nil {
log.Fatalf(
"JSON marshaling failed: %s", err)
}
fmt.Printf("%s\n", data)
var titles []struct{
Title string
// Actors []string
}
if err := json.Unmarshal(
data, &titles); err != nil {
log.Fatalf(
"JSON unmarshaling failed: %s",err)
}
fmt.Println(titles)
}
ch4.5 JSON p108/127 of