Home > Backend Development > Golang > How to skip error fields during 'Unmarshal' in go?

How to skip error fields during 'Unmarshal' in go?

WBOY
Release: 2024-02-09 09:00:20
forward
408 people have browsed it

如何在 go 中的“Unmarshal”期间跳过错误字段?

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.

Question content

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"`
}
Copy after login

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 }
Copy after login

I just want to get the price value from the structure but leave the quantity as the initial default value.

Solution

You can't.

If your JSON contains floats, you cannot unmarshal them to ints at all. you must:

  1. Use float64 and handle non-integers in code after unmarshalling
  2. Write your own UnmarshalJSON for your type
  3. Perform a two-step unmarshalling, once ignoring ("-") 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!

Related labels:
source:stackoverflow.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template