Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions go/study/ch04_json/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/tecyokomichi/WebAppLearning/go/study/ch04_json

go 1.19
82 changes: 82 additions & 0 deletions go/study/ch04_json/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package main

import (
"encoding/json"
"fmt"
"os"
)

type Person struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Birthday string `json:"birthday"`
Age int `json:"age"`
}

func main() {
if len(os.Args) < 2 {
showHelp()
os.Exit(1)
}
switch os.Args[1] {
case "example":
people := []*Person {
{
FirstName: "Blake",
LastName: "Serild",
Birthday: "1989-07-10",
Age: 33,
},
{
FirstName: "Libbie",
LastName: "Drisko",
Birthday: "1988-06-15",
Age: 24,
},
{
FirstName: "Anestassia",
LastName: "Truc",
Birthday: "1973-04-02",
Age: 48,
},
}

b, err := json.MarshalIndent(people, "", "\t")
if err != nil {
fmt.Printf("Error: %v", err)
os.Exit(1)
}
fmt.Println(string(b))
case "summary":
var people []*Person
if len(os.Args) < 3 || len(os.Args) > 3 {
showHelp()
os.Exit(1)
}
f, err := os.ReadFile(os.Args[2])
if err != nil {
fmt.Printf("Error: %v", err)
os.Exit(1)
}
err = json.Unmarshal(f, &people)
if err != nil {
fmt.Printf("Error: %v", err)
os.Exit(1)
}
count, sum := 0, 0
for _, p := range people {
count++
sum += p.Age
}
fmt.Printf("%d 人、平均年齢 %d \n", count, sum/count)
default:
showHelp()
os.Exit(1)
}
}

func showHelp() {
fmt.Printf("Usage:\n")
fmt.Printf("%s example\n", os.Args[0])
fmt.Printf("Shows an example of JSON data\n")
}
32 changes: 32 additions & 0 deletions go/study/ch04_json/people.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
[
{
"first_name": "Blake",
"last_name": "Serilda",
"birthday": "1989-07-10",
"age": 33
},
{
"first_name": "Libbie",
"last_name": "Drisko",
"birthday": "1998-06-15",
"age": 24
},
{
"first_name": "Anestassia",
"last_name": "Truc",
"birthday": "1973-04-02",
"age": 48
},
{
"first_name": "Cyndie",
"last_name": "Syd",
"birthday": "1985-07-12",
"age": 37
},
{
"first_name": "Joelly",
"last_name": "Honoria",
"birthday": "2012-01-31",
"age": 10
}
]