An article explaining golang's json operation in detail

PHPz
Release: 2023-03-29 16:14:03
forward
906 people have browsed it

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.

An article explaining golang's json operation in detail

##golang’s json operation

JSON is a

lightweight 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))}
Copy after login
Print: After serialization: {"Name": "tom", "Age": 12, "Skill": "football"}

(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)}
Copy after login

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 a

tag 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))}
Copy after login
, you can see that the name of the key has changed to the name of the tag label we specified

After serialization: {"stu_name":"tom ","stu_age":12,"Skill":"football"}

2. Convert map to JSON
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}
Copy after login

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.
Example:

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"}}
Copy after login
Through printing, we found that lowercase variables, such as age and addr, were not converted into json data.

Summary:

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"}}

(2) Add additional Field
data, _ = 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"}

(3) Merge two structs
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))}
Copy after login

Merge two structs: {"u_name":"admin","password":"pwd","email" : "user@163.com", "Age": 23, "addr": "Shanghai"}

(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

(5) A json is divided into two structs
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)
Copy after login

is divided into two structs: User={system abc user2@163.com}, Person={23 Hangzhou}

Recommended study: "

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!