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 {

func (b *NullBool) UnmarshalJSON(data []byte) error {
  b.Bool = bool(data) //BREAKS!! 
  b.Valid = true
  return nil


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

Answered By – Paul Hankin

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.