An article explaining golang's json operation in detail
This article brings you relevant knowledge about golang, and mainly introduces to you the json operation of golang. Friends who are interested can take a look at it together. I hope it will be helpful to everyone.
##golang’s json operation
JSON is alightweight data exchange format. Easy to read and write. golang provides the encoding/json package to operate JSON data.
1. Convert structure to JSON
(1) Use the json.Marshal() method to convert the structure into a JSON string
import ( "encoding/json" "fmt")type Student struct { Name string Age int Skill string}func main() { stu := Student{"tom", 12, "football"} data, err := json.Marshal(&stu) if err != nil { fmt.Printf("序列化错误 err=%v\n", err) return } fmt.Println("序列化后: ", string(data))}
(2) JSON To convert a string into a structure, you can use the json.Unmarshal() method
func main() { str := `{"Name":"tom","Age":12,"Skill":"football"}` var stu2 Student err := json.Unmarshal([]byte(str), &stu2) if err != nil { fmt.Printf("反序列化错误 err=%v\n", err) return } fmt.Printf("反序列化后: Student=%v, Name=%v\n", stu2, stu2.Name)}
to print: After deserialization: Student={tom 12 football} , Name=tom
(3) How to realize that the name of the key can be customized after the structure is serialized
For the name of the customized key, you can specify it in the struct variable After printing atag label
type Student struct { Name string `json:"stu_name"` Age int `json:"stu_age"` Skill string // 也可以不指定 tag标签,默认就是 变量名称}func main() { stu := Student{"tom", 12, "football"} data, err := json.Marshal(&stu) if err != nil { fmt.Printf("序列化错误 err=%v\n", err) return } fmt.Println("序列化后: ", string(data))}
After serialization: {"stu_name":"tom ","stu_age":12,"Skill":"football"}
2. Convert map to JSONfunc main() {
// map 转 Json字符串
m := make(map[string]interface{})
m["name"] = "jetty"
m["age"] = 16
data, err := json.Marshal(&m)
if err != nil {
fmt.Printf("序列化错误 err=%v\n", err)
return
}
fmt.Println("序列化后: ", string(data)) // 打印: 序列化后: {"age":16,"name":"jetty"}
// Json字符串 转 map
str := `{"age":25,"name":"car"}`
err = json.Unmarshal([]byte(str), &m)
if err != nil {
fmt.Printf("反序列化错误 err=%v\n", err)
return
}
fmt.Printf("反序列化后: map=%v, name=%v\n", m, m["name"])
// 打印: 反序列化后: map=map[age:25 name:car], name=car}
Copy after login
func main() { // map 转 Json字符串 m := make(map[string]interface{}) m["name"] = "jetty" m["age"] = 16 data, err := json.Marshal(&m) if err != nil { fmt.Printf("序列化错误 err=%v\n", err) return } fmt.Println("序列化后: ", string(data)) // 打印: 序列化后: {"age":16,"name":"jetty"} // Json字符串 转 map str := `{"age":25,"name":"car"}` err = json.Unmarshal([]byte(str), &m) if err != nil { fmt.Printf("反序列化错误 err=%v\n", err) return } fmt.Printf("反序列化后: map=%v, name=%v\n", m, m["name"]) // 打印: 反序列化后: map=map[age:25 name:car], name=car}
3. Can the variables of the structure be converted into json data without tags?
- If the first letter of the variable is lowercase, it is private. Because the reflection information cannot be obtained, it cannot be transferred.
- If the first letter of the variable is capitalized, it is public. It can be converted normally regardless of whether tags are added or not. Variables with tags will be displayed according to the name of the tag.
type User struct { Name string `json:"u_name"` age int `json:"u_age"` Skill string // 也可以不指定 tag标签,默认就是 变量名称 addr string}func main() { user := User{"admin", 23, "football", "上海"} data, err := json.Marshal(&user) if err != nil { fmt.Printf("序列化错误 err=%v\n", err) return } fmt.Println("序列化后: ", string(data)) // 打印: 序列化后: {"u_name":"admin","Skill":"football"}}
If the first letter is lowercase, it cannot be converted to json data regardless of whether it is added with a tag, while if it is uppercase, it can be aliased with a tag, and if it is not added with a tag, it will be converted into json data. The fields are consistent with the original names of the structure variables
4. Some tips for JSON operations
(1) Ignore the specified fields of the struct type User struct {
Name string `json:"u_name"`
Password string `json:"password"`
Email string `json:"email"`}func main() {
user := User{"admin", "pwd", "user@163.com"}
person := Person{23, "上海"}
// 忽略掉 Password 字段
data, _ := json.Marshal(struct {
*User
Password string `json:"password,omitempty"`
}{User: &user})
fmt.Println("忽略字段: ", string(data)) // 打印: 忽略字段: {"u_name":"admin","email":"user@163.com"}}
Copy after login
Ignore fields: {"u_name":"admin","email":"user@163.com"}}
type User struct { Name string `json:"u_name"` Password string `json:"password"` Email string `json:"email"`}func main() { user := User{"admin", "pwd", "user@163.com"} person := Person{23, "上海"} // 忽略掉 Password 字段 data, _ := json.Marshal(struct { *User Password string `json:"password,omitempty"` }{User: &user}) fmt.Println("忽略字段: ", string(data)) // 打印: 忽略字段: {"u_name":"admin","email":"user@163.com"}}
(2) Add additional Fielddata, _ = json.Marshal(struct {
*User
Skill string `json:"skill"` // 临时添加额外的 Skill字段}{
User: &user,
Skill: "football",})fmt.Println("添加额外字段: ", string(data))
Copy after login
Add additional fields: {"u_name":"admin","password":"pwd","email":"user@163.com","skill":"football"}
data, _ = json.Marshal(struct { *User Skill string `json:"skill"` // 临时添加额外的 Skill字段}{ User: &user, Skill: "football",})fmt.Println("添加额外字段: ", string(data))
(3) Merge two structstype User struct {
Name string `json:"u_name"`
Password string `json:"password"`
Email string `json:"email"`}type Person struct {
Age int
Addr string `json:"addr"`}func main() {
// 初始化两个 struct
user := User{"admin", "pwd", "user@163.com"}
person := Person{23, "上海"}
data, _ := json.Marshal(struct {
*User *Person }{
User: &user,
Person: &person,
})
fmt.Println("合并两个struct: ", string(data))}
Copy after login
Merge two structs: {"u_name":"admin","password":"pwd","email" : "user@163.com", "Age": 23, "addr": "Shanghai"}
type User struct { Name string `json:"u_name"` Password string `json:"password"` Email string `json:"email"`}type Person struct { Age int Addr string `json:"addr"`}func main() { // 初始化两个 struct user := User{"admin", "pwd", "user@163.com"} person := Person{23, "上海"} data, _ := json.Marshal(struct { *User *Person }{ User: &user, Person: &person, }) fmt.Println("合并两个struct: ", string(data))}
(4) The string is passed to the int type emp := struct { // 创建匿名 struct
Num int `json:"num,string"`}{15,}data, _ := json.Marshal(&emp)fmt.Println("数字转成字符串: ", string(data)) // 数字转成字符串: {"num":"15"}str := `{"Num":"25"}`_ = json.Unmarshal([]byte(str), &emp)fmt.Printf("字符串转成数字: Emp.Num=%v\n", emp.Num) // 字符串转成数字: Emp.Num=25
Copy after login
emp := struct { // 创建匿名 struct Num int `json:"num,string"`}{15,}data, _ := json.Marshal(&emp)fmt.Println("数字转成字符串: ", string(data)) // 数字转成字符串: {"num":"15"}str := `{"Num":"25"}`_ = json.Unmarshal([]byte(str), &emp)fmt.Printf("字符串转成数字: Emp.Num=%v\n", emp.Num) // 字符串转成数字: Emp.Num=25
(5) A json is divided into two structsstr = ` {"u_name":"system","password":"abc","email":"user2@163.com","Age":23,"addr":"杭州"}`var user2 Uservar person2 Person_ := json.Unmarshal([]byte(str), &struct {
*User *Person}{
User: &user2,
Person: &person2,})fmt.Printf("分成两个struct: User=%v, Person=%v\n", user2, person2)
Copy after login
is divided into two structs: User={system abc user2@163.com}, Person={23 Hangzhou}
str = ` {"u_name":"system","password":"abc","email":"user2@163.com","Age":23,"addr":"杭州"}`var user2 Uservar person2 Person_ := json.Unmarshal([]byte(str), &struct { *User *Person}{ User: &user2, Person: &person2,})fmt.Printf("分成两个struct: User=%v, Person=%v\n", user2, person2)
go video tutorial"
The above is the detailed content of An article explaining golang's json operation in detail. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...
