3

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
}

3 Answers 3

9

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
}
4

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
}
0

It think the simple way is to check the slice length like so:

b := []byte("data")
isByteSliceValid := len(b) != 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.