go JSONの分析と作成
2585 ワード
package main
import (
"fmt"
"encoding/json"
"os"
"io/ioutil"
"io"
)
type Post struct {
Id int `json:"id"`
Content string `json:"content"`
Author Author `json:"author"`
Comments []Comment `json:"comments"`
}
type Author struct {
Id int `json:"id"`
Name string `json:"name"`
}
type Comment struct {
Id int `json:"id"`
Content string `json:"content"`
Author string `json:"author"`
}
func main() {
// JSON
post :=Post {
Id: 1,
Content:"Hello World!",
Author: Author{
Id: 2,
Name: "shao tong",
},
Comments: []Comment{
Comment{
Id:3,
Content:"Have a great day!",
Author:"Adam",
},
Comment{
Id:4,
Content:"How are tyyou today?!",
Author:"Betty",
},
},
}
// :
output,err := json.MarshalIndent(&post,"","\t\t")
if err != nil {
fmt.Println("Error marshalling to JSON:",err)
return
}
err = ioutil.WriteFile("post1.json",output,0644)
if err != nil {
fmt.Println("Error writing JSON to file:",err)
return
}
// :
jsonFile,err :=os.Create("post2.json")
if err != nil {
fmt.Println("Error creating JSON file:",err)
return
}
encoder :=json.NewEncoder(jsonFile)
err = encoder.Encode(&post)
if err != nil {
fmt.Println("Error encoding JSON to file:",err)
return
}
// JSON
// :
jsonFile1,err := os.Open("post.json")
if err != nil {
fmt.Println("Error opening JSON file",err)
return
}
defer jsonFile1.Close()
jsonData1,err :=ioutil.ReadAll(jsonFile1)
if err != nil {
fmt.Println("Error reading JSON data :",err)
return
}
var post1 Post
json.Unmarshal(jsonData1, &post1)
fmt.Println(post1)
// :
decoder :=json.NewDecoder(jsonFile1)
for {
var post Post
err :=decoder.Decode(&post)
if err == io.EOF {
break
}
if err != nil {
fmt.Println("Error decoding JSON:",err)
return
}
fmt.Println(post)
}
}