当前位置:网站首页>Golang对JSON文件的读写操作
Golang对JSON文件的读写操作
2022-06-23 15:38:00 【学亮编程手记】
Go语言JSON文件的读写操作
写
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/"}}}
// 创建文件
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("编码成功")
}
}
读
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)
}
}
/** 解码成功 [{Golang http://c.biancheng.net/golang/ [http://c.biancheng.net/cplus/ http://c.biancheng.net/linux_tutorial/]} {Java http://c.biancheng.net/java/ [http://c.biancheng.net/socket/ http://c.biancheng.net/python/]}] `` */
边栏推荐
- [tcapulusdb knowledge base] Introduction to tmonitor background one click installation (II)
- Sleuth + Zipkin
- 线程池
- Log4J日志整合及配置详解
- Block, non block, multiplexing, synchronous, asynchronous, bio, NiO, AIO
- 泰山OFFICE技术讲座:使用字体斜体的四种情形
- R语言ggplot2可视化水平箱图(Horizontal boxplot with coord_flip)、并添加抖动数据点显示分布情况(jittered points)
- 【TcaplusDB知识库】Tmonitor单机安装指引介绍(二)
- 证券开户的优惠怎样才能得到?在线开户安全么?
- 【TcaplusDB知识库】Tmonitor系统升级介绍
猜你喜欢

513. Find Bottom Left Tree Value

【TcaplusDB知识库】Tmonitor后台一键安装介绍(一)

XML

Tips for accelerating file transfer between windows remote desktop connections

线上交流丨可信机器学习之机器学习与知识推理相结合(青源Talk第20期 李博)

【TcaplusDB知识库】Tmonitor后台一键安装介绍(二)

《ThreadLocal》

阻塞、非阻塞、多路复用、同步、异步、BIO、NIO、AIO 一文搞定

安全舒适,全新一代奇骏用心诠释老父亲的爱

Sleuth + Zipkin
随机推荐
生成二叉搜索平衡树[利用树递归特性]
机器人方向与高考选专业的一些误区
mysql事务与锁
How to quickly respond to changing production management needs?
Can the hbuilderx light theme be annotated?
XML
Batch registration component
readImg: 读取图片到Variable变量
openGauss数据库源码解析系列文章—— 密态等值查询技术详解(下)
阻塞、非阻塞、多路复用、同步、异步、BIO、NIO、AIO 一文搞定
ABP框架之——数据访问基础架构(下)
Introduction to asynccontext
Web articles_ 01 understanding web development
MySQL transactions and locks
安全舒适,全新一代奇骏用心诠释老父亲的爱
AsyncContext简介
SSRS页面配置Postgresql data source的方法
Do you understand Mipi c-phy protocol? One of the high-speed interfaces for mobile phones
解读2022年度敏捷教练行业现状报告
Tableau comparatif du nom de la clé ADB, du numéro du Code de la clé et de la description de la clé