Table of Contents
##golang’s json operation" >##golang’s json operation
1. Convert structure to JSON" >1. Convert structure to JSON
3. Can the variables of the structure be converted into json data without tags? " >3. Can the variables of the structure be converted into json data without tags?
4. Some tips for JSON operations" >4. Some tips for JSON operations
Home Backend Development Golang An article explaining golang's json operation in detail

An article explaining golang's json operation in detail

Mar 29, 2023 pm 02:24 PM
golang json

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

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.

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

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

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

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. �...

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

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,...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

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

PostgreSQL monitoring method under Debian PostgreSQL monitoring method under Debian Apr 02, 2025 am 07:27 AM

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

How to specify the database associated with the model in Beego ORM? How to specify the database associated with the model in Beego ORM? Apr 02, 2025 pm 03:54 PM

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

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

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

See all articles