package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"strconv"
)
type Study struct{
CourseName string `json:"CourseName"`
Score int `json:"Score"`
}
type Student struct{
Name string `json:"name"`
Address string `json:"addr"`
ScoreList []Study `json:"ScoreList"`
Num int `json:"Num"`
}
func checkError(err error){
if err != nil{
panic(err)
}
}
func readFromJson(src string){
data,err:= ioutil.ReadFile(src)
checkError(err)
newStu := &Student{}
err = json.Unmarshal(data,&newStu)
checkError(err)
fmt.Println(newStu.Name+"的学习情况")
for _,v := range newStu.ScoreList{
fmt.Println("Course:" + v.CourseName + "\tScore:" + strconv.Itoa(v.Score))
}
fmt.Println(newStu.ScoreList[0].CourseName)
}
func writeToJson(src string){
stu := &Student{
Name: "George",
Address: "北京",
ScoreList: []Study{{"语文",21},{"数学",22}},
}
stu.Num = len(stu.ScoreList)
data,err := json.MarshalIndent(stu,""," ") // 第二个表示每行的前缀,这里不用,第三个是缩进符号,这里用tab
checkError(err)
err = ioutil.WriteFile(src,data,0777)
checkError(err)
}
func main(){
src := "Json/b.json"
//writeToJson(src)
readFromJson(src)
}
golang 读写json文件
最新推荐文章于 2024-08-15 17:36:25 发布