Currently am mapping the output of a service that, lets say, liberally interchanges 0 and false (and 1 and true) for its boolean types. Is there a way to use a more permissive parser for the built in encoding/json unmarshal function? I've tried adding ,string to the json tags to no avail.
An example of what I'd want:
type MyType struct {
AsBoolean bool `json:"field1"`
AlsoBoolean bool `json:"field2"`
}
then, given input json:
{
"field1" : true,
"field2" : 1
}
the resulting struct would be:
obj := MyType{}
json_err := json.Unmarshal([]byte(input_json), &obj)
fmt.Printf("%v\n", obj.AsBoolean) //"true"
fmt.Printf("%v\n", obj.AlsoBoolean) //"true"
This is my take on it. In case you need something to deal with a few extra cases. Add more as needed.
// so you know what's needed.
import (
"encoding/json"
"strconv"
"strings"
)
// NumBool provides a container and unmarshalling for fields that may be
// boolean or numbrs in the WebUI API.
type NumBool struct {
Val bool
Num float64
}
// UnmarshalJSON parses fields that may be numbers or booleans.
func (f *NumBool) UnmarshalJSON(b []byte) (err error) {
switch str := strings.ToLower(strings.Trim(string(b), `"`)); str {
case "true":
f.Val = true
case "false":
f.Val = false
default:
f.Num, err = strconv.ParseFloat(str, 64)
if f.Num > 0 {
f.Val = true
}
}
return err
}
See it in playground.
I've also been known to something like this:
// FlexBool provides a container and unmarshalling for fields that may be
// boolean or strings in the Unifi API.
type FlexBool struct {
Val bool
Txt string
}
// UnmarshalJSON method converts armed/disarmed, yes/no, active/inactive or 0/1 to true/false.
// Really it converts ready, ok, up, t, armed, yes, active, enabled, 1, true to true. Anything else is false.
func (f *FlexBool) UnmarshalJSON(b []byte) error {
if f.Txt = strings.Trim(string(b), `"`); f.Txt == "" {
f.Txt = "false"
}
f.Val = f.Txt == "1" || strings.EqualFold(f.Txt, "true") || strings.EqualFold(f.Txt, "yes") ||
strings.EqualFold(f.Txt, "t") || strings.EqualFold(f.Txt, "armed") || strings.EqualFold(f.Txt, "active") ||
strings.EqualFold(f.Txt, "enabled") || strings.EqualFold(f.Txt, "ready") || strings.EqualFold(f.Txt, "up") ||
strings.EqualFold(f.Txt, "ok")
return nil
}
And if you want to go real small:
// Bool allows 0/1 and "0"/"1" and "true"/"false" (strings) to also become boolean.
type Bool bool
func (bit *Bool) UnmarshalJSON(b []byte) error {
// txt := string(b) // original, no strings.
txt := string(bytes.Trim(b, `"`))
*bit = Bool(txt == "1" || txt == "true")
return nil
}
See this one in playground: bool/int/string. The old version: playground: bool/int.
Thank you Will Charzuck for the answer, however, it did not work for me unless I used a pointer method receiver, and set the value of the pointer in the function body.
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
}
Ended up using a special "boolean" type, and where I was using a normal bool, swapped for this:
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With