当前位置:网站首页>Go language JSON package usage
Go language JSON package usage
2022-04-23 17:52:00 【Liu Yuanshan】
Catalog
Serialization and deserialization
1、 serialize
1) Structure data transfer JSON, Property must start with public uppercase
Use Person The structure describes the user information and transfers it to JSON
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string
Age int
Rmb float64
Sex bool
Hobby []string
}
func main() {
person := Person{
" Yu Qian ", 50, 123.45, true, []string{
" smoking ", " Drink ", " Hot head "}}
bytes, e := json.Marshal(person)
if e != nil {
fmt.Println(" Serialization failure ,err=", e)
return
}
fmt.Println(string(bytes))
}
2)Map Data transfer JSON
Use map[string]interface{} Describe the user information and transfer to JSON
package main
import (
"encoding/json"
"fmt"
)
func main() {
dataMap := make(map[string]interface{
})
dataMap["name"] = " Yu Qian "
dataMap["age"] = 50
dataMap["rmb"] = 123.45
dataMap["sex"] = true
dataMap["hobby"] = []string{
" smoking ", " Drink ", " Hot head "}
bytes, e := json.Marshal(dataMap)
if e != nil {
fmt.Println(" Serialization failure ,err=", e)
return
}
fmt.Println(string(bytes))
}
3)map Slice data to JSON
Use map The slice describes multiple user information and transfers it to JSON
package main
import (
"encoding/json"
"fmt"
)
func main() {
dataMap1 := make(map[string]interface{
})
dataMap1["name"] = " Steel balls "
dataMap1["hobby"] = []string{
" Smoke Chinese ", " Drink Niulan mountain ", " Hot embossing roll head "}
dataMap2 := make(map[string]interface{
})
dataMap2["name"] = " Son of a bitch "
dataMap2["hobby"] = []string{
" Smoke Yuxi ", " Drink Wuliangye ", " Burn Matt "}
dataMap3 := make(map[string]interface{
})
dataMap3["name"] = " Bastard "
dataMap3["hobby"] = []string{
" Smoke the panda ", " Drink Jiannanchun ", " Scald the chicken crown "}
dataSlice := make([]map[string]interface{
}, 0)
dataSlice = append(dataSlice, dataMap1, dataMap2, dataMap3)
bytes, e := json.Marshal(dataSlice)
if e != nil {
fmt.Println(" Serialization failure ,err=", e)
return
}
fmt.Println(string(bytes))
}
2、 Deserialization
1)JSON Transfer structure data
package main
import (
"encoding/json"
"fmt"
)
var jsonStr = `{"Name":" Yu Qian ","Age":50,"Rmb":123.45,"Sex":true,"Hobby":[" smoking "," Drink "," Hot head "]}`
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(" Deserialization failure ,err=", err)
return
}
fmt.Println(*personPtr)
}
2)JSON turn map data
package main
import (
"encoding/json"
"fmt"
)
var jsonStr = `{"Name":" Yu Qian ","Age":50,"Rmb":123.45,"Sex":true,"Hobby":[" smoking "," Drink "," Hot head "]}`
func main() {
jsonBytes := []byte(jsonStr)
dataMap := make(map[string]interface{
})
err := json.Unmarshal(jsonBytes, &dataMap)
if err != nil {
fmt.Println(" Deserialization failure ,err=", err)
return
}
fmt.Println(dataMap)
}
3)JSON Turn slice data
package main
import (
"encoding/json"
"fmt"
)
func main() {
jsonStr := `[{"hobby":[" Smoke Chinese "," Drink Niulan mountain "," Hot embossing roll head "],"name":" Steel balls "},{"hobby":[" Smoke Yuxi "," Drink Wuliangye "," Burn Matt "],"name":" Son of a bitch "},{"hobby":[" Smoke the panda "," Drink Jiannanchun "," Scald the chicken crown "],"name":" Bastard "}]`
jsonBytes := []byte(jsonStr)
dataSlice := make([]map[string]interface{
}, 0)
err := json.Unmarshal(jsonBytes, &dataSlice)
if err != nil {
fmt.Println(" Deserialization failure ,err=", err)
return
}
fmt.Println(dataSlice)
}
Reading and writing JSON file
1、 code
1) take map The data goes to JSON The encoded data is written to JSON In file
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
dataMap := make(map[string]interface{
})
dataMap["name"] = " Yu Qian "
dataMap["age"] = 50
dataMap["rmb"] = 123.45
dataMap["sex"] = true
dataMap["hobby"] = []string{
" smoking ", " Drink ", " Hot head "}
// Create and open the target JSON file
dstFile, _ := os.OpenFile("D:/go_work/src/demo/1.json", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
defer dstFile.Close()
// Create the encoder of the target file
encoder := json.NewEncoder(dstFile)
// take Go Language data is encoded into JSON file
err := encoder.Encode(dataMap)
// Judge whether the coding is successful
if err != nil {
fmt.Println(" Encode data to JSON File failed ,err=", err)
return
}
fmt.Println(" Coding succeeded !")
}
2) Convert structure slice data to JSON The encoded data is written to JSON In file
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
type Person struct {
Name string
Age int
Rmb float64
Sex bool
Hobby []string
}
p1 := Person{
" Steel balls ", 30, 123.45, false, []string{
" Smoke Chinese ", " Drink farmer spring ", " Hot taro "}}
p2 := Person{
" Son of a bitch ", 30, 123.45, false, []string{
" Smoke Yuxi ", " Drink Le Pak ", " Hot hands "}}
p3 := Person{
" Bastard ", 30, 123.45, false, []string{
" Draw gold leaves ", " Drink Sanlu milk ", " Burn your head "}}
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)
// Judge whether the coding is successful
if err != nil {
fmt.Println(" Encode data to JSON File failed ,err=", err)
return
}
fmt.Println(" Coding succeeded !")
}
2、 decode
1) take JSON The data in the file is read as map data
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
// Open storage JSON Source file of data
srcFile, _ := os.Open("D:/go_work/src/demo/1.json")
defer srcFile.Close()
// establish map, Used to receive decoded data
dataMap := make(map[string]interface{
})
// Create a decoder for the source file
decoder := json.NewDecoder(srcFile)
// Decode the data in the source file , Throw in dataMap In memory
err := decoder.Decode(&dataMap)
// Get the decoding result
if err != nil {
fmt.Println(" Decoding failed ,err=", err)
return
}
fmt.Println(" Decoding successful :", dataMap)
}
fmt.Println(" Decoding successful :", dataMap)
}
2) take JSON The data in the file is read into sliced data
Pay attention to whether the data is suitable for slicing
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
type Person struct {
Name string
Age int
Rmb float64
Sex bool
Hobby []string
}
// Open storage JSON Source file of data
srcFile, _ := os.Open("D:/go_work/src/demo/2.json")
defer srcFile.Close()
// Create variables for receiving data
people := make([]Person, 0)
// Create a decoder for the source file
decoder := json.NewDecoder(srcFile)
// Decode the data in the source file , Throw in dataMap In memory
err := decoder.Decode(&people)
// Get the decoding result
if err != nil {
fmt.Println(" Decoding failed ,err=", err)
return
}
fmt.Println(" Decoding successful :", people)
}
版权声明
本文为[Liu Yuanshan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231751425143.html
边栏推荐
- Read software engineering at Google (15)
- uni-app黑马优购项目学习记录(下)
- 圆环回原点问题-字节跳动高频题
- Add animation to the picture under V-for timing
- In embedded system, must the program code in flash be moved to ram to run?
- Kubernetes service discovery monitoring endpoints
- 470. 用 Rand7() 实现 Rand10()
- 极致体验,揭晓抖音背后的音视频技术
- Detailed deployment of flask project
- Leak detection and vacancy filling (VII)
猜你喜欢
开源按键组件Multi_Button的使用,含测试工程
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!!!)
Allowed latency and side output
Welcome to the markdown editor
双指针进阶--leetcode题目--盛最多水的容器
958. 二叉树的完全性检验
Laser slam theory and practice of dark blue College Chapter 3 laser radar distortion removal exercise
1217_使用SCons生成目标文件
394. 字符串解码-辅助栈
编译原理 求first集 follow集 select集预测分析表 判断符号串是否符合文法定义(有源码!!!)
随机推荐
Vite configure proxy proxy to solve cross domain
20222 return to the workplace
2021长城杯WP
MySQL advanced index [classification, performance analysis, use, design principles]
[二叉数] 二叉树的最大深度+N叉树的最大深度
Where is the configuration file of tidb server?
Sword finger offer 22 The penultimate node in the linked list - speed pointer
Click Cancel to return to the previous page and modify the parameter value of the previous page, let pages = getcurrentpages() let prevpage = pages [pages. Length - 2] / / the data of the previous pag
云原生虚拟化:基于 Kubevirt 构建边缘计算实例
Halo 开源项目学习(二):实体类与数据表
402. Remove K digits - greedy
Encapsulate a timestamp to date method on string prototype
剑指 Offer 22. 链表中倒数第k个节点-快慢指针
Sword finger offer 03 Duplicate number in array
一些问题一些问题一些问题一些问题
Uniapp custom search box adaptation applet alignment capsule
239. 滑动窗口最大值(困难)-单向队列、大顶堆-字节跳动高频题
开期货,开户云安全还是相信期货公司的软件?
31. 下一个排列
Future usage details