当前位置:网站首页>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
边栏推荐
- Sword finger offer 03 Duplicate number in array
- Qt error: /usr/bin/ld: cannot find -lGL: No such file or directory
- QT modification UI does not take effect
- 587. 安装栅栏 / 剑指 Offer II 014. 字符串中的变位词
- 剑指 Offer 22. 链表中倒数第k个节点-快慢指针
- 209. Minimum length subarray - sliding window
- 土地覆盖/利用数据产品下载
- flink 学习(十二)Allowed Lateness和 Side Output
- MySQL进阶学习之SQL优化【插入,主键,排序,分组,分页,计数】
- 209. 长度最小的子数组-滑动窗口
猜你喜欢

Tell the truth of TS

470. Rand10() is implemented with rand7()

Element calculation distance and event object

Flask项目的部署详解

土地覆盖/利用数据产品下载

HCIP第五次实验

2022 judgment questions and answers for operation of refrigeration and air conditioning equipment

2022年茶艺师(初级)考试模拟100题及模拟考试

Learning record of uni app dark horse yougou project (Part 2)

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
随机推荐
386. 字典序排数(中等)-迭代-全排列
HCIP第五次实验
开期货,开户云安全还是相信期货公司的软件?
Operation of 2022 mobile crane driver national question bank simulation examination platform
flink 学习(十二)Allowed Lateness和 Side Output
Timestamp to formatted date
2022 judgment questions and answers for operation of refrigeration and air conditioning equipment
1217_ Generating target files using scons
20222 return to the workplace
剑指 Offer 03. 数组中重复的数字
超分之TDAN
Halo 开源项目学习(二):实体类与数据表
双指针进阶--leetcode题目--盛最多水的容器
41. 缺失的第一个正数
Summary of common SQL statements
[binary number] maximum depth of binary tree + maximum depth of n-ary tree
The JS timestamp of wechat applet is converted to / 1000 seconds. After six hours and one day, this Friday option calculates the time
Cross domain settings of Chrome browser -- including new and old versions
一些问题一些问题一些问题一些问题
Use of list - addition, deletion, modification and query