In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "what is the JSON processing method in Go". In the daily operation, I believe that many people have doubts about what the JSON processing method is in Go. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "what is the JSON processing method in Go?" Next, please follow the editor to study!
Go language has built-in support for JSON. Using the encoding/json standard library built into the GE language, developers can easily use Go programs to generate and parse data in JSON format. When implementing the coding and decoding of JSON in GE language, it follows the standard of RFC4627 protocol.
Basic serialization
First, let's look at the basic usage of json.Marshal () (serialization) and json.Unmarshal (deserialization) in the Go language.
Type Person struct {Name stringAge int64Weight float64} func main () {p1: = Person {Name: "Xiaoming", Age: 18type Person struct weight: 71.5,} / / struct-> json stringb, err: = json.Marshal (p1) if err! = nil {fmt.Printf ("json.Marshal failed, err:%v\ n", err) return} fmt.Printf ("str:%s\ n", b) / / json string-> structvar p2 Personerr = json.Unmarshal (b) & p2) if err! = nil {fmt.Printf ("json.Unmarshal failed, err:%v\ n", err) return} fmt.Printf ("p2VV\ n", p2)}
Output: str: {"Name": "Xiaoming", "Age": 18, "Weight": 71.5} p2:main.Person {Name: "Xiaoming", Age:18, Weight:71.5}
Introduction to structure tag
Tag is the meta-information of a structure, which can be read at run time through the mechanism of reflection. Tag is defined after the structure field and is surrounded by a pair of backquotes in the following format:
`key1: "value1" key2: "value2" `
The structure tag consists of one or more key-value pairs. Keys and values are separated by colons, and values are enclosed in double quotation marks. Multiple key-value pairs can be set in the same structure field, and different key-value pairs can be separated by spaces.
Specify a field name using json tag
Serialization and deserialization use the field name of the structure by default, and we can specify the field name generated by json serialization by adding tag to the structure field.
/ / use json tag to specify the behavior of serialization and deserialization type Person struct {Name string `json: "name" `/ / specify json serialization / deserialization using lowercase nameAge int64Weight float64} ignore a field
If you want to ignore a field in the structure during json serialization / deserialization, you can add-to the tag as follows.
/ / use json tag to specify the behavior of json serialization and deserialization type Person struct {Name string `json: "name" `/ / specify that json serialization / deserialization use lowercase nameAge int64Weight float64 `json: "-"` / / specify that this field is ignored when json serialization / deserialization} ignore null field
When fields in struct have no value, json.Marshal () does not ignore these fields when serializing, but instead defaults to the type zero value of the field (for example, the zero value of int and float type is zero string is "", and the zero value of object type is nil). If you want to ignore these fields with no values when serializing, you can add omitempty tag to the corresponding fields. For example:
Type User struct {Name string `json: "name" `Email string `json: "email" `Hobby [] string `json: "hobby" `} func omitemptyDemo () {U1: = User {Name: "Xiaoming",} / / struct-> json stringb, err: = json.Marshal (U1) if err! = nil {fmt.Printf ("json.Marshal failed, err:%v\ n", err) return} fmt.Printf ("str:%s\ n", b)}
Output result: str: {"name": "Xiaoming", "email": "", "hobby": null}
If you want to remove the null value field from the final serialization result, you can define the structure as follows:
/ / add omitempty to tag to ignore null values / / Note that the hobby,omitempty adds up to json tagged values, with type User struct {Name string `json: "name" `Email string `json: "email,omitempty" `Hobby [] string `json: "hobby,omitempty" `} separated by commas.
At this point, execute the above omitemptyDemo, and the output is as follows: str: {"name": "Xiaoming"} / / there are no email and hobby fields in the serialization result.
To put it beside the point, when we use gorm to operate the database, we often encounter problems that want to ignore the modification of specified fields, such as the associated entities in the structure, which only want to be displayed in json, and ignore entities when form is submitted. I will sort out this problem separately.
Ignore nested structure body null value field
First, let's take a look at several examples of structure nesting:
Type User struct {Name string `json: "name" `Email string `json: "email,omitempty" `Hobby [] string `json: "hobby,omitempty" `Profile} type Profile struct {Website string `json: "site" `Slogan string `json: "slogan" `} func nestedStructDemo () {U1: = User {Name: "Xiaoming", Hobby: [] string {"football", "basketball"},} b, err: = json.Marshal (U1) if err! = nil {fmt.Printf ("json.Marshal failed, err:%v\ n") Err) return} fmt.Printf ("str:%s\ n", b)}
When anonymously nesting Profile, the serialized json string is monolayer: str: {"name": "Xiao Ming", "hobby": ["football", "basketball"], "site": "", "slogan": ""}
To become a nested json string, you need to change to named nesting or define the field tag:
Type User struct {Name string `json: "name" `Email string `json: "email,omitempty" `Hobby [] string `json: "hobby,omitempty" `Profile `json: "profile" `} / / str: {"name": "Xiaoming", "hobby": ["football", "basketball"], "profile": {"site": "," slogan ":"}}"
If you want to ignore this field when the nested structure is null, it is not enough to add omitempty:
Type User struct {Name string `json: "name" `Email string `json: "email,omitempty" `Hobby [] string `json: "hobby,omitempty" `Profile `json: "profile,omitempty" `} / / str: {"name": "Xiaoming", "hobby": ["football", "basketball"], "profile": {"site": "," slogan ":"}}"
You also need to use nested structure pointers:
Type User struct {Name string `json: "name" `Email string `json: "email,omitempty" `Hobby [] string `json: "hobby,omitempty" `* Profile `json: "profile,omitempty" `/ / here is the key point} / / str: {"name": "Xiaoming", "hobby": ["football", "basketball"]} do not modify the original structure to ignore null fields
We need json to serialize User, but we do not want to serialize the password and do not want to modify the User structure. At this time, we can create another structure, PublicUser, anonymously nest the original User, specify the Password field as the anonymous structure pointer type, and add omitemptytag. The example code is as follows:
Type User struct {Name string `json: "name" `Password string `json: "password" `} type PublicUser struct {* User / / anonymously nested Password * struct {} `json: "password,omitempty"`} func omitPasswordDemo () {ul: = User {Name: "Xiaoming", Password: "123456",} b, err: = json.Marshal (PublicUser {User: & U1}) if err! = nil {fmt.Printf ("json.Marshal U1 failed, err:%v\ n") Err) return} fmt.Printf ("str:%s\ n", b) / / str: {"name": "Xiaoming"}} graceful handling of numbers in string format
Sometimes, the front end may use a number of string type in the passed json data, and then you can add string to the structure tag to tell the json package to parse the data of the corresponding field from the string:
Type Card struct {ID int64 `json: "id,string" `/ / add string tagScore float64 `json: "score,string"` / / add string tag} func intAndStringDemo () {jsonStr1: = `{"id": "1234567", "score": "88.50"} `var C1 Cardif err: = json.Unmarshal ([] byte (jsonStr1), & C1) Err! = nil {fmt.Printf ("json.Unmarsha jsonStr1 failed, err:%v\ n", err) return} fmt.Printf ("C1 json.Unmarsha jsonStr1 failed% ID:1234567\ n", C1) / / c1:main.Card {ID:1234567, Score:88.5}} at this point, the study of "what is the JSON processing method in Go" is over. I hope to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.