Skip to content

JSON column to struct #372

Answered by jacobmolby
trentclowater asked this question in Q&A
Discussion options

You must be logged in to vote

You can try something like this:

package mytypes

type History struct {
	ID      int64
	Network []Item
}

type Item struct {
	Key    string  `json:"key"`
	Name   string  `json:"name"`
	Values []Value `json:"values"`
}

type Value struct {
	Key   string `json:"key"`
	Name  string `json:"name"`
	Value string `json:"value"`
}

func (h *History) Scan(value any) error {
	bytes, ok := value.([]byte)
	if !ok {
		return fmt.Errorf("value is not []byte")
	}

        return json.Unmarshal(bytes, &h)
}

func (h History) Value() (driver.Value, error) {
	return json.Marshal(h)
}

Then in your bobgen config file you should do the following:

types:
  mytypes.History:
    no_randomization_test: true
    i…

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
1 reply
@stephenafamo
Comment options

Answer selected by stephenafamo
Comment options

You must be logged in to vote
2 replies
@jacobmolby
Comment options

@trentclowater
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants