Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang - How to convert byte slice to bool?

Tags:

go

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
}
like image 342
sat Avatar asked Sep 01 '25 10:09

sat


2 Answers

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
}
like image 170
Elwinar Avatar answered Sep 04 '25 02:09

Elwinar


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
}
like image 39
Paul Hankin Avatar answered Sep 04 '25 03:09

Paul Hankin