Home > Article > Backend Development > 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.
lightweight data exchange format. Easy to read and write. golang provides the encoding/json package to operate JSON data.
(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))}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)}
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))}, 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"}
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}
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"}}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
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"}}
data, _ = json.Marshal(struct { *User Skill string `json:"skill"` // 临时添加额外的 Skill字段}{ User: &user, Skill: "football",})fmt.Println("添加额外字段: ", string(data))
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))}
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
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!