'golang - How to convert byte slice to bool?
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
}
Solution 1:[1]
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
}
Solution 2:[2]
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
}
Solution 3:[3]
It think the simple way is to check the slice length like so:
b := []byte("data")
isByteSliceValid := len(b) != 0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Paul Hankin |
Solution 2 | Elwinar |
Solution 3 | Lucas Picollo |