go语言读取json文件的方法
package main import ( "encoding/json" "fmt" "io/ioutil" "os" ) type Post struct { //带结构标签,反引号来包围字符串 Id int `json:"id"` Content string `json:"content"` Author Author `json:"author"` Comment []Comment `json:"comments"` } type Author struct { Id int `json:"id"` Name string `json:"name"` } type Comment struct { Id int `json:"id"` Content string `json:"content"` Author string `json:"author"` } func main() { jsonFile, err := os.Open("json/post.json") if err != nil { fmt.Println("error opening json file") return } defer jsonFile.Close() jsonData, err := ioutil.ReadAll(jsonFile) if err!= nil { fmt.Println("error reading json file") return } var post Post json.Unmarshal(jsonData,&post) fmt.Println(post) }
json
{ "id": 1, "content": "hello golang", "author": { "id": 2, "name": "miller Fan" }, "comments": [ { "id": 3, "content": "Have a good night", "author": "屈原" }, { "id": 4, "content": "道德经", "author": "老子" } ] }
https://blog.csdn.net/weixin_41670928/article/details/122569045