package main import ( "encoding/json" "fmt" "os" ) //将于谦的信息map写入到一个json文件 func main021() { dataMap := make(map[string]interface{}) dataMap["name"]= "于谦" dataMap["rmb"]= 123.55 dataMap["age"]= 50 dataMap["hobby"]= []string{"抽烟","喝酒","烫头"} //打开或创建目标文件 dastFile, _ := os.OpenFile("E:/go-project/daemon/w3/于谦.json", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666) defer dastFile.Close() //创建一个编码器 encoder := json.NewEncoder(dastFile) err := encoder.Encode(dataMap) if err != nil{ fmt.Println("编码失败,err=",err) return } fmt.Println("编码成功") } //将由结构体组成的切片写入到一个json文件 func main() { type Persion struct { Name string Age int Sex bool Hobby []string Rmb float64 } p1 := Persion{"王刚蛋", 30, false, []string{"抽中华", "喝怡宝", "烫头"}, 123.45} p2 := Persion{"王铁蛋", 30, false, []string{"抽玉溪", "喝农夫山泉", "烫鸡冠头"}, 123.45} p3 := Persion{"王铜蛋", 30, false, []string{"抽利群", "喝娃哈哈", "烫波浪"}, 123.45} persions := make([]Persion, 0) persions = append(persions, p1, p2, p3) dstFile, _ := os.OpenFile("E:/go-project/daemon/w3/八大姨.json", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666) defer dstFile.Close() encoder := json.NewEncoder(dstFile) err := encoder.Encode(persions) if err != nil { fmt.Println("编码失败,err=",err) return } fmt.Println("编码成功") }
请发表评论