当前位置:网站首页>Go语言JSON包使用
Go语言JSON包使用
2022-04-23 17:51:00 【刘远山】
目录
序列化与反序列化
1、序列化
1)结构体数据转JSON,属性必须是公有的大写开头
使用Person结构体描述用户信息并转JSON
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string
Age int
Rmb float64
Sex bool
Hobby []string
}
func main() {
person := Person{
"于谦", 50, 123.45, true, []string{
"抽烟", "喝酒", "烫头"}}
bytes, e := json.Marshal(person)
if e != nil {
fmt.Println("序列化失败,err=", e)
return
}
fmt.Println(string(bytes))
}
2)Map数据转JSON
使用map[string]interface{}描述用户信息并转JSON
package main
import (
"encoding/json"
"fmt"
)
func main() {
dataMap := make(map[string]interface{
})
dataMap["name"] = "于谦"
dataMap["age"] = 50
dataMap["rmb"] = 123.45
dataMap["sex"] = true
dataMap["hobby"] = []string{
"抽烟", "喝酒", "烫头"}
bytes, e := json.Marshal(dataMap)
if e != nil {
fmt.Println("序列化失败,err=", e)
return
}
fmt.Println(string(bytes))
}
3)map切片数据转JSON
使用map切片描述多个用户信息并转JSON
package main
import (
"encoding/json"
"fmt"
)
func main() {
dataMap1 := make(map[string]interface{
})
dataMap1["name"] = "王钢蛋"
dataMap1["hobby"] = []string{
"抽中华", "喝牛栏山", "烫花卷头"}
dataMap2 := make(map[string]interface{
})
dataMap2["name"] = "王铁蛋"
dataMap2["hobby"] = []string{
"抽玉溪", "喝五粮液", "烫杀马特"}
dataMap3 := make(map[string]interface{
})
dataMap3["name"] = "王铜蛋"
dataMap3["hobby"] = []string{
"抽小熊猫", "喝剑南春", "烫鸡冠头"}
dataSlice := make([]map[string]interface{
}, 0)
dataSlice = append(dataSlice, dataMap1, dataMap2, dataMap3)
bytes, e := json.Marshal(dataSlice)
if e != nil {
fmt.Println("序列化失败,err=", e)
return
}
fmt.Println(string(bytes))
}
2、反序列化
1)JSON转结构体数据
package main
import (
"encoding/json"
"fmt"
)
var jsonStr = `{"Name":"于谦","Age":50,"Rmb":123.45,"Sex":true,"Hobby":["抽烟","喝酒","烫头"]}`
func main() {
type Person struct {
Name string
Age int
Rmb float64
Sex bool
Hobby []string
}
jsonBytes := []byte(jsonStr)
personPtr := new(Person)
err := json.Unmarshal(jsonBytes, personPtr)
if err != nil {
fmt.Println("反序列化失败,err=", err)
return
}
fmt.Println(*personPtr)
}
2)JSON转map数据
package main
import (
"encoding/json"
"fmt"
)
var jsonStr = `{"Name":"于谦","Age":50,"Rmb":123.45,"Sex":true,"Hobby":["抽烟","喝酒","烫头"]}`
func main() {
jsonBytes := []byte(jsonStr)
dataMap := make(map[string]interface{
})
err := json.Unmarshal(jsonBytes, &dataMap)
if err != nil {
fmt.Println("反序列化失败,err=", err)
return
}
fmt.Println(dataMap)
}
3)JSON转切片数据
package main
import (
"encoding/json"
"fmt"
)
func main() {
jsonStr := `[{"hobby":["抽中华","喝牛栏山","烫花卷头"],"name":"王钢蛋"},{"hobby":["抽玉溪","喝五粮液","烫杀马特"],"name":"王铁蛋"},{"hobby":["抽小熊猫","喝剑南春","烫鸡冠头"],"name":"王铜蛋"}]`
jsonBytes := []byte(jsonStr)
dataSlice := make([]map[string]interface{
}, 0)
err := json.Unmarshal(jsonBytes, &dataSlice)
if err != nil {
fmt.Println("反序列化失败,err=", err)
return
}
fmt.Println(dataSlice)
}
读写JSON文件
1、编码
1)将map数据转为JSON编码数据写入到JSON文件中
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
dataMap := make(map[string]interface{
})
dataMap["name"] = "于谦"
dataMap["age"] = 50
dataMap["rmb"] = 123.45
dataMap["sex"] = true
dataMap["hobby"] = []string{
"抽烟", "喝酒", "烫头"}
//创建并打开目标JSON文件
dstFile, _ := os.OpenFile("D:/go_work/src/demo/1.json", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
defer dstFile.Close()
//创建目标文件的编码器
encoder := json.NewEncoder(dstFile)
//将Go语言数据编码到JSON文件
err := encoder.Encode(dataMap)
//判断编码是否成功
if err != nil {
fmt.Println("编码数据到JSON文件失败,err=", err)
return
}
fmt.Println("编码成功!")
}
2)将结构体切片数据转为JSON编码数据写入到JSON文件中
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
type Person struct {
Name string
Age int
Rmb float64
Sex bool
Hobby []string
}
p1 := Person{
"王钢蛋", 30, 123.45, false, []string{
"抽中华", "喝农夫山泉", "烫芋头"}}
p2 := Person{
"王铁蛋", 30, 123.45, false, []string{
"抽玉溪", "喝乐百氏", "烫手"}}
p3 := Person{
"王铜蛋", 30, 123.45, false, []string{
"抽黄金叶", "喝三鹿牛奶", "烫光头"}}
people := make([]Person, 0)
people = append(people, p1, p2, p3)
dstFile, _ := os.OpenFile("D:/go_work/src/demo/2.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
defer dstFile.Close()
encoder := json.NewEncoder(dstFile)
err := encoder.Encode(people)
//判断编码是否成功
if err != nil {
fmt.Println("编码数据到JSON文件失败,err=", err)
return
}
fmt.Println("编码成功!")
}
2、解码
1)将JSON文件中的数据读取成map数据
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
//打开存储JSON数据的源文件
srcFile, _ := os.Open("D:/go_work/src/demo/1.json")
defer srcFile.Close()
//创建map,用于接收解码好的数据
dataMap := make(map[string]interface{
})
//创建源文件的解码器
decoder := json.NewDecoder(srcFile)
//解码源文件中的数据,丢入dataMap所在的内存
err := decoder.Decode(&dataMap)
//获取解码结果
if err != nil {
fmt.Println("解码失败,err=", err)
return
}
fmt.Println("解码成功:", dataMap)
}
fmt.Println("解码成功:", dataMap)
}
2)将JSON文件中的数据读取成切片数据
要注意数据是否适合转切片
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
type Person struct {
Name string
Age int
Rmb float64
Sex bool
Hobby []string
}
//打开存储JSON数据的源文件
srcFile, _ := os.Open("D:/go_work/src/demo/2.json")
defer srcFile.Close()
//创建用于接数据的变量
people := make([]Person, 0)
//创建源文件的解码器
decoder := json.NewDecoder(srcFile)
//解码源文件中的数据,丢入dataMap所在的内存
err := decoder.Decode(&people)
//获取解码结果
if err != nil {
fmt.Println("解码失败,err=", err)
return
}
fmt.Println("解码成功:", people)
}
版权声明
本文为[刘远山]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_39218464/article/details/124352497
边栏推荐
猜你喜欢
Qt 修改UI没有生效
极致体验,揭晓抖音背后的音视频技术
440. The k-th small number of dictionary order (difficult) - dictionary tree - number node - byte skipping high-frequency question
JS forms the items with the same name in the array object into the same array according to the name
Qt error: /usr/bin/ld: cannot find -lGL: No such file or directory
Compilation principle first set follow set select set prediction analysis table to judge whether the symbol string conforms to the grammar definition (with source code!!!)
Anchor location - how to set the distance between the anchor and the top of the page. The anchor is located and offset from the top
394. String decoding - auxiliary stack
2022年流动式起重机司机国家题库模拟考试平台操作
Allowed latency and side output
随机推荐
极致体验,揭晓抖音背后的音视频技术
ES6 face test questions (reference documents)
Operation of 2022 mobile crane driver national question bank simulation examination platform
开期货,开户云安全还是相信期货公司的软件?
Leak detection and vacancy filling (VIII)
JS get link? The following parameter name or value, according to the URL? Judge the parameters after
239. Maximum value of sliding window (difficult) - one-way queue, large top heap - byte skipping high frequency problem
Timestamp to formatted date
Applet learning notes (I)
列錶的使用-增删改查
Matlab / Simulink simulation of double closed loop DC speed regulation system
In ancient Egypt and Greece, what base system was used in mathematics
ES6 new method
102. Sequence traversal of binary tree
Halo open source project learning (II): entity classes and data tables
Kubernetes 服务发现 监控Endpoints
470. Rand10() is implemented with rand7()
92. 反转链表 II-字节跳动高频题
关于gcc输出typeid完整名的方法
587. 安装栅栏 / 剑指 Offer II 014. 字符串中的变位词