当前位置:网站首页>Golang writes to JSON files

Golang writes to JSON files

2022-06-23 16:23:00 Learn programming notes

Go Language JSON Read and write operation of the file

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://c.biancheng.net/golang/", []string{
    "http://c.biancheng.net/cplus/", "http://c.biancheng.net/linux_tutorial/"}}, {
    "Java", "http://c.biancheng.net/java/", []string{
    "http://c.biancheng.net/socket/", "http://c.biancheng.net/python/"}}}

//  create a file 

filePtr, err := os.Create("info.json")

if err != nil {
    

fmt.Println(" File creation failed ", err.Error())

return

}

defer filePtr.Close()

//  establish  json  Encoder 

encoder := json.NewEncoder(filePtr)

err = encoder.Encode(info)

if err != nil {
    

fmt.Println(" Coding errors ", err.Error())

} else {
    

fmt.Println(" Coding succeeded ")

}

}

info.json:
 Insert picture description here

原网站

版权声明
本文为[Learn programming notes]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231538135040.html