栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

go语言读取json文件的方法

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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": "老子"
    }
  ]
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/902593.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号