Home >Backend Development >Golang >How Can I Customize JSON Unmarshaling to Handle Ambiguous Boolean Values?

How Can I Customize JSON Unmarshaling to Handle Ambiguous Boolean Values?

Barbara Streisand
Barbara StreisandOriginal
2024-11-29 05:49:09249browse

How Can I Customize JSON Unmarshaling to Handle Ambiguous Boolean Values?

Expanding Boolean Parsing Options in JSON Unmarshaling

When mapping service outputs that blur the lines between boolean types and other values, a more accommodating JSON parser becomes essential. The built-in encoding/json unmarshal function falls short in this regard, prompting the search for permissive parsing alternatives.

One approach is to create a custom UnmarshalJSON function for the desired type. This function can define custom parsing rules to handle the ambiguous boolean values. For instance, consider the following ConvertibleBoolean type:

type ConvertibleBoolean bool

func (bit *ConvertibleBoolean) UnmarshalJSON(data []byte) error {
    asString := string(data)
    if asString == "1" || asString == "true" {
        *bit = true
    } else if asString == "0" || asString == "false" {
        *bit = false
    } else {
        return errors.New(fmt.Sprintf("Boolean unmarshal error: invalid input %s", asString))
    }
    return nil
}

In this function, strings "1" and "true" are mapped to true, while "0" and "false" are parsed as false. Values outside these ranges trigger an error.

To utilize this custom boolean parsing, apply a json tag to the target field. For example:

type MyType struct {
    AsBoolean ConvertibleBoolean `json:"field1"`
    AlsoBoolean ConvertibleBoolean `json:"field2"`
}

With these custom parsing rules in place, the JSON input:

{
    "field1": true,
    "field2": 1
}

Will produce the following unmarshaled struct:

obj := MyType{}
json_err := json.Unmarshal([]byte(input_json), &obj)
fmt.Printf("%v\n", obj.AsBoolean) //"true"
fmt.Printf("%v\n", obj.AlsoBoolean) //"true"

By leveraging custom parsing functions, you gain flexibility in JSON unmarshaling, allowing you to handle ambiguous boolean values as needed.

The above is the detailed content of How Can I Customize JSON Unmarshaling to Handle Ambiguous Boolean Values?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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