当前位置:网站首页>Go语言JSON文件的读写操作
Go语言JSON文件的读写操作
2022-08-10 01:51:00 【wangwei830】
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于阅读和编写,同时也易于机器解析和生成。它基于 JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999 的一个子集。
JSON 是一种使用 UTF-8 编码的纯文本格式,采用完全独立于语言的文本格式,由于写起来比 XML 格式方便,并且更为紧凑,同时所需的处理时间也更少,致使 JSON 格式越来越流行,特别是在通过网络连接传送数据方面。
开发人员可以使用 JSON 传输简单的字符串、数字、布尔值,也可以传输一个数组或者一个更复杂的复合结构。在 Web 开发领域中,JSON 被广泛应用于 Web 服务端程序和客户端之间的数据通信。
Go语言内建对 JSON 的支持,使用内置的 encoding/json 标准库,开发人员可以轻松使用Go程序生成和解析 JSON 格式的数据。
JSON 结构如下所示:
{
"key1":"value1","key2":value2,"key3":["value3","value4","value5"]}
写 JSON 文件
使用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("编码成功")
}
}
运行上面的代码会在当前目录下生成一个 info.json 文件,文件内容如下:
[
{
"Name":"Golang",
"Url":"http://c.biancheng.net/golang/",
"Course":[
"http://c.biancheng.net/golang/102/",
"http://c.biancheng.net/golang/concurrent/"
]
},
{
"Name":"Java",
"Url":"http://c.biancheng.net/java/",
"Course":[
"http://c.biancheng.net/java/10/",
"http://c.biancheng.net/python/"
]
}
]
读 JSON 文件
读 JSON 数据与写 JSON 数据一样简单,示例代码如下:
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)
}
}
运行结果如下:
go run main.go
解码成功
[{
Golang http://c.biancheng.net/golang/ [http://c.biancheng.net/golang/102/ http://c.biancheng.net/golang/concurrent/]} {
Java http://c.biancheng.net/java/ [http://c.biancheng.net/java/10/ http://c.biancheng.net/python/]}]
顺便提一下,还有一种叫做 BSON (Binary JSON) 的格式与 JSON 非常类似,与 JSON 相比,BSON 着眼于提高存储和扫描效率。BSON 文档中的大型元素以长度字段为前缀以便于扫描。在某些情况下,由于长度前缀和显式数组索引的存在,BSON 使用的空间会多于 JSON。
边栏推荐
猜你喜欢
【论文粗读】(NeurIPS 2020) SwAV:对比聚类结果的无监督视觉特征学习
RESOURCE_EXHAUSTED: etcdserver: mvcc: database space exceeded
Nacos源码分析专题(五)-Nacos小结
[LeetCode] Find the sum of the numbers from the root node to the leaf node
牛客刷题——剑指offer(第四期)
Research on Ethernet PHY Chip LAN8720A Chip
Unity顶点动画
sql实战积累
781. 森林中的兔子
【web渗透】SSRF漏洞超详细讲解
随机推荐
hint: Updates were rejected because the tip of your current branch is behind hint: its remote counte
FusionConpute虚拟机的发放与管理
空间复杂度为O(1)的归并排序
JCMsuite—单模光纤传播模式
OOD论文:Revisit Overconfidence for OOD Detection
【论文笔记】基于深度学习的机器人抓取虚拟仿真实验教学系统
基于设计稿识别的可视化低代码系统实践
数组(一)
C# rounding MidpointRounding.AwayFromZero
grafana9配置邮箱告警
微透镜阵列后光传播的研究
Not, even the volume of the king to write code in the company are copying and pasting it reasonable?
Unity reports Unsafe code may only appear if compiling with /unsafe. Enable “Allow ‘unsafe’ code” in Pla
SQL注入的order by ,limit与宽字节注入
中文NER的SOTA:RICON
OpenSSF的开源软件风险评估工具:Scorecards
UXDB现在支持函数索引吗?
华为HCIE云计算之FC添加ipsan数据存储
阿里云OSS文件上传
.Net面试经验总结