Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the omitempty keyword in Golang

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "how to use the omitempty keyword in Golang". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Usage

Friends who are familiar with Golang must be familiar with the conversion between json and struct. In order to decouple the structure in the code from the json data, we usually add an explanation after the field type of the structure. For example, when representing an address, the json data is as follows

{"street": "200 Larkin St", "city": "San Francisco", "state": "CA", "zipcode": "94102"}

The corresponding Golang structure may look like this

Type address struct {Street string `json: "street" `/ / Street Ste string `json: "suite"` / / Unit (may not exist) City string `json: "city" `/ / City State string `json: "state"` / State / Provincial Zipcode string `json: "zipcode" `/ / Postal Code}

In this way, no matter how the variables in the code change, we can successfully parse the json data to get the correct street, city and other information, so far everything is normal. But if we want to restore the address structure to json format, the problem arises. For example, we read the address json with the following code, and then print it back to normal json after processing it according to the business logic.

Func main () {data: = `{"street": "200Larkin St", "city": "San Francisco", "state": "CA", "zipcode": "94102"} `addr: = new (address) json.Unmarshal ([] byte (data), & addr) / / deals with addr variables. AddressBytes, _: = json.MarshalIndent (addr, ",") fmt.Printf ("% s\ n", string (addressBytes))}

The output of this code is

{"street": "200 Larkin St", "suite": "", "city": "San Francisco", "state": "CA", "zipcode": "94102"}

There is an extra line "suite": ", and this information is not available in the original json data (in American addresses, it is normal that suite does not exist if it is not for group renting apartments or shared office buildings, and it is enough for people to use street numbers to indicate addresses), but what we prefer is that when an address has a suite number, it will not be output when there is no suite. Fortunately, it will not be output when there is no suite. We can add the omitempty keyword to the structure definition of Golang to indicate that if this information is not provided, do not include its default value when serializing to json. With a little modification, the address structure becomes

Type address struct {Street string `json: "street" `Ste string `json: "suite,omitempty" `City string `json: "city" `State string `json: "state" `Zipcode string `json: "zipcode" `}

Rerun to get the correct results.

Trap

While bringing convenience, there are also some pitfalls in using omitempty. One is that the keyword cannot ignore nested structures. Let's talk about the address type. This time we want to add a new field to the address structure to represent latitude and longitude. If there is no lack of relevant data, we can ignore it for the time being. The new struct definition is as follows

Type address struct {Street string `json: "street" `Ste string `json: "suite,omitempty" `City string `json: "city" `State string `json: "state" `Zipcode string `json: "zipcode" `Coordinate coordinate `json: "coordinate,omitempty" `} type coordinate struct {Lat float64 `json: "latitude" `Lng float64 `json: "longitude"`}

After reading the original address data and serializing the output, we will find that even if the omitempty keyword is added, the output json still carries an empty coordinate information.

{"street": "200 Larkin St", "city": "San Francisco", "state": "CA", "zipcode": "94102", "coordinate": {"latitude": 0, "longitude": 0}}

In order to achieve the desired effect, we can define the coordinates as the pointer type, so that Golang can know what the "null value" of a pointer is, otherwise Golang will not be able to guess the null value we want in the face of a custom structure. So we have the following definition of structure

Type address struct {Street string `json: "street" `Ste string `json: "suite,omitempty" `City string `json: "city" `State string `json: "state" `Zipcode string `json: "zipcode" `Coordinate * coordinate `json: "coordinate,omitempty" `} type coordinate struct {Lat float64 `json: "latitude" `Lng float64 `json: "longitude"`}

The corresponding output is

{"street": "200 Larkin St", "city": "San Francisco", "state": "CA", "zipcode": "94102"}

Another "trap" is that for a field defined in omitempty, if the value assigned to it happens to be equal to the default null value, the field will not be output after it is converted to json. For example, the latitude and longitude coordinate structure defined above, if we add omitempty to both latitude and longitude field

Type coordinate struct {Lat float64 `json: "latitude,omitempty" `Lng float64 `json: "longitude,omitempty" `}

Then we were very interested in the "origin coordinates" of the Gulf of Guinea in Africa, so we wrote the following code

Func main () {cData: = `{"latitude": 0.0, "longitude": 0.0} `c: = new (coordinate) json.Unmarshal ([] byte (cData), & c) / / specific processing logic. CoordinateBytes, _: = json.MarshalIndent (c, ",") fmt.Printf ("% s\ n", string (coordinateBytes))}

Finally, we got one.

{}

The coordinates are gone! But our assumption is that if a location does not have latitude and longitude information, it will be suspended, which is no problem, but for the "origin coordinates", we still ignore (0.0,0.0) when we know exactly its latitude and longitude. The correct way to write is to change the definition in the body of the structure to a pointer.

Type coordinate struct {Lat * float64 `json: "latitude,omitempty" `Lng * float64 `json: "longitude,omitempty" `}

In this way, the null value changes from 0. 0 of float64 to nil of pointer type, and we can see the correct longitude and latitude output.

{"latitude": 0, "longitude": 0} "how to use the omitempty keyword in Golang" is introduced here. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report