In the process of JSON deserialization (Unmarshal) using Go language, sometimes we may encounter some error fields that cannot be processed. These error fields may cause the program to terminate, affecting the normal execution of the code. So, is there any way we can skip these error fields during the Unmarshal process? The answer is yes. This article will introduce you to how to use some techniques in the Go language to skip error fields encountered during Unmarshal. Let's continue reading.
I am using json.Unmarshal(body, outputStruct)
to convert a byte array into a structure. Errors may occur during unmarshalling.
For example, the structure is:
type Item struct { Price float64 `json:"price"` Quantity int `json:"quantity"` }
If I pass quantity
as a floating point value instead of an integer, it throws an error. I want to know how to unmarshal only valid fields and skip fields with errors?
So if I unmarshal a json:
{ price: 10, quantity: 2.5 }
I just want to get the price
value from the structure but leave the quantity as the initial default value.
You can't.
If your JSON contains floats, you cannot unmarshal them to ints at all. you must:
"-"
) Quantity
so that it doesn't fail and only do the second unmarshaling of the Quantity (the new structure) group and ignore errors. 2 is the "best" way, but I'm not sure what's the logic behind "skipping fields of wrong type"? If quantity is 2.5, what will be the value of quantity? 0? Why?
The above is the detailed content of How to skip error fields during 'Unmarshal' in go?. For more information, please follow other related articles on the PHP Chinese website!