I have a database sql.NullBool. To unmarshal json into it, I am writing this little function. I can converty the byte array to string by simply casting it (string(data))...not so for bool. Any idea how I can convert to bool?
type NullBool struct {
sql.NullBool
}
func (b *NullBool) UnmarshalJSON(data []byte) error {
b.Bool = bool(data) //BREAKS!!
b.Valid = true
return nil
}
The simplest way would be to use the strconv.ParseBool
package. Like this:
func (b *NullBool) UnmarshalJSON(data []byte) error {
var err error
b.Bool, err = strconv.ParseBool(string(data))
b.Valid = (err == nil)
return err
}
You can use the json module almost directly.
func (nb *NullBool) UnmarshalJSON(data []byte) error {
err := json.Unmarshal(data, &nb.Bool)
nb.Valid = (err == nil)
return err
}
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