6-4 json读写文件(解码)
package main import ( "encoding/json" "fmt" "os" ) //解码于谦.json 为map func main041() { //打开要解码的文件 srcFile, _ := os.Open("E:/go-project/daemon/w3/于谦.json") defer srcFile.Close() //创建一个解码器 decoder := json.NewDecoder(srcFile) //于谦.json文件是一个map类型的json,创建解码文件后存放的map dstMap := make(map[string]interface{}) //解码源文件,丢入对应的map所在的地址 err := decoder.Decode(&dstMap) if err != nil{ fmt.Printf("解码失败,err=",err) return } fmt.Println("解码成功:",dstMap) } //解码八大姨.json 文件结构体切片 func main() { type Persion struct { Name string Age int Sex bool Hobby []string Rmb float64 } //打开要解码的文件 srcFile, _ := os.Open("E:/go-project/daemon/w3/八大姨.json") defer srcFile.Close() //创建一个解码器 decoder := json.NewDecoder(srcFile) dstSlice := make([]Persion, 0) //解码源文件,丢入对应的map所在的地址 err := decoder.Decode(&dstSlice) if err != nil{ fmt.Println("解码失败,err=",err) return } fmt.Println("解码成功:",dstSlice) }