0

I am trying to read columns to an embedded struct usng gorm, the table has a Json column and I would like to read it a defined struct. How can I achieve this one ??

type Permissions struct {
   // all other columns 
   Rules []Rule // this is saved as a json column in db  
}

type Rule struct {
  // embedded columns here too 
}

1
  • 1
    You would need to have a string in your gorm struct for the json column and then unmarshal the json into the according struct. Commented Aug 25, 2021 at 5:22

1 Answer 1

2

Custom data types are supported, you would just need to implement the Scanner and Valuer interfaces for your custom type. It could look something like this:

func (r *Rule) Scan(value interface{}) error {
  val, ok := value.([]byte)
  if !ok {
    return errors.New(fmt.Sprint("Failed to unmarshal string value:", value))
  }

  return json.Unmarshal([]byte(val), r)
}

func (r Rule) Value() (driver.Value, error) {
  val, err := json.Marshal(&r)
  if err != nil {
    return nil, err
  }
  
  return val, nil
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.