Go has the built-in capability of mapping json directly to fields in a structure. Additionally, you can specify that only specific fields are mapped, ignoring all others.
Here is what using this feature looks like:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strings"
)
type JsonData []struct {
Sha string `json:"sha"`
Commit struct {
Author struct {
Name string `json:"name"`
Date string `json:"date"`
} `json:"author"`
}
}
func main() {
var jsonData JsonData
jsonFile, err := os.Open("commits.json")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer jsonFile.Close()
jsonBytes, _ := ioutil.ReadAll(jsonFile)
if err = json.Unmarshal(jsonBytes, &jsonData); err != nil {
fmt.Println(err)
os.Exit(1)
}
for _, item := range jsonData {
fmt.Println(strings.Repeat("-", 50))
fmt.Println("Name:", item.Commit.Author.Name)
fmt.Println("Commit Date:", item.Commit.Author.Date)
fmt.Println("SHA Hash:", item.Sha)
}
fmt.Println(strings.Repeat("-", 50))
}
I think that, for the most part, someone not familiar with go can look at the code above and have a decent understanding of what it's doing.
The more I study go, the more I like it...
AIR.