JSON column to struct #372
-
What is the best way, using bob, create a model that transforms the contents of a jsonb column in the database into a struct in the model? (I'm using Postgres if that makes any difference). For example, if there is a history table with a column named network, with contents like: [
{
"key": "interface",
"name": "Network Interface",
"values": [
{
"key": "mac_address",
"name": "MAC Address",
"value": "00:01:02:03:04:05"
}
]
},
{
"key": "interface",
"name": "Network Interface",
"values": [
{
"key": "mac_address",
"name": "MAC Address",
"value": "01:02:03:04:05:06"
}
]
}
] I would like the generated models.History to look like this: 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"`
} So that instead of Network being types.JSON[json.RawMessage], it gets unmarshalled into a struct. Is that even possible? Or am I thinking about this the wrong way, and I should be doing something else? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
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
imports: ['mytypes "abc/mytypes"']
random_expr: |
return mytypes.History{}
compare_expr: |-
reflect.DeepEqual(AAA, BBB)
compare_expr_imports: ['"reflect"']
replacements:
- tables: ["my_table"]
match:
name: "history"
replace: "mytypes.History" |
Beta Was this translation helpful? Give feedback.
-
Thanks for the answer. I had about 99% of that correct already. The problem turned out to be that I thought the But it seems that That was not really clear from the documentation, and I left it out of the question because I thought I could just make the custom type Also, I noticed I made a typo and typed |
Beta Was this translation helpful? Give feedback.
You can try something like this:
Then in your bobgen config file you should do the following: