go语言读取json文件的方法
·
1、读取文件的代码
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)
}
2、测试的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": "老子"
}
]
}
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐



所有评论(0)