{"key1":"value1","key2":value2,"key3":["value3","value4","value5"]}
package main import ( "encoding/json" "fmt" "os" ) type Website struct { Name string `xml:"name,attr"` Url string Course []string } func main() { info := []Website{{"Golang", "http://task.lmcjl.com/golang/", []string{"http://task.lmcjl.com/cplus/", "http://task.lmcjl.com/linux_tutorial/"}}, {"Java", "http://task.lmcjl.com/java/", []string{"http://task.lmcjl.com/socket/", "http://task.lmcjl.com/python/"}}} // 创建文件 filePtr, err := os.Create("info.json") if err != nil { fmt.Println("文件创建失败", err.Error()) return } defer filePtr.Close() // 创建Json编码器 encoder := json.NewEncoder(filePtr) err = encoder.Encode(info) if err != nil { fmt.Println("编码错误", err.Error()) } else { fmt.Println("编码成功") } }运行上面的代码会在当前目录下生成一个 info.json 文件,文件内容如下:
[
{
"Name":"Golang",
"Url":"http://task.lmcjl.com/golang/",
"Course":[
"http://task.lmcjl.com/golang/102/",
"http://task.lmcjl.com/golang/concurrent/"
]
},
{
"Name":"Java",
"Url":"http://task.lmcjl.com/java/",
"Course":[
"http://task.lmcjl.com/java/10/",
"http://task.lmcjl.com/python/"
]
}
]
package main import ( "encoding/json" "fmt" "os" ) type Website struct { Name string `xml:"name,attr"` Url string Course []string } func main() { filePtr, err := os.Open("./info.json") if err != nil { fmt.Println("文件打开失败 [Err:%s]", err.Error()) return } defer filePtr.Close() var info []Website // 创建json解码器 decoder := json.NewDecoder(filePtr) err = decoder.Decode(&info) if err != nil { fmt.Println("解码失败", err.Error()) } else { fmt.Println("解码成功") fmt.Println(info) } }运行结果如下:
go run main.go
解码成功
[{Golang http://task.lmcjl.com/golang/ [http://task.lmcjl.com/golang/102/ http://task.lmcjl.com/golang/concurrent/]} {Java http://task.lmcjl.com/java/ [http://task.lmcjl.com/java/10/ http://task.lmcjl.com/python/]}]
本文链接:http://task.lmcjl.com/news/15339.html