Home > Backend Development > Golang > How Can I Unmarshal Flexible Boolean Values (0/1 and true/false) from JSON in Go?

How Can I Unmarshal Flexible Boolean Values (0/1 and true/false) from JSON in Go?

Linda Hamilton
Release: 2024-12-04 17:42:12
Original
633 people have browsed it

How Can I Unmarshal Flexible Boolean Values (0/1 and true/false) from JSON in Go?

JSON Unmarshalling of Flexible Boolean Values

When dealing with JSON data sources that inconsistently represent boolean values as both 0/1 and false/true, the standard encoding/json package may not provide sufficient flexibility for parsing. To address this issue, we can implement a custom UnmarshalJSON method to expand the accepted boolean formats.

In the example provided, we define a struct named MyType with two boolean fields: AsBoolean and AlsoBoolean. The corresponding JSON input contains the values "true" and "1" for the respective fields.

To unmarshal both 0 and false as booleans, we create a new type ConvertibleBoolean and implement its UnmarshalJSON method. Within the method, we inspect the input data as a string and determine the corresponding boolean value based on the following conditions:

  • If the string is "1" or "true," we set the boolean value to true.
  • If the string is "0" or "false," we set the boolean value to false.
  • Any other input results in an error with a descriptive message.

By customizing the UnmarshalJSON method, we can extend the default JSON unmarshaling behavior and accommodate the non-standard boolean representations in the input JSON data. This approach allows us to unmarshal the JSON input into the expected boolean values and populate the MyType struct accordingly.

The above is the detailed content of How Can I Unmarshal Flexible Boolean Values (0/1 and true/false) from JSON in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template