2

I somehow managed to make this works , but not exactly as intended. Code below is "poco" for data in JSONB column.

type post struct {
    Title       string   `json:"title"`
    Tags        []string `json:"tags"`
}

Below i have initialization of slice of posts as well as single post for scaning each row into. The rest is standard query code. This data is column name that is declared as jsonb

var t post
var h []post
rows, err := conpool.Query("SELECT data FROM post")
if err != nil {
    fmt.Println(err)
}
defer rows.Close()
for rows.Next() {
    if err := rows.Scan(&t); err != nil {
        fmt.Println(err)
    }
    h = append(h, t)
}
for _, v := range h {
    fmt.Println(v.Title,v.Tags)
}

Output i get:

First Title [qwe asd]
Second Title [qwe asd]
Third Title [qwe asd]

As you can see above , output of each tag slice is the same , since slice is just a pointer to underlying array last one that get pulled out of db overwrites previous ones. I know that if i declare post as Tags [2]string it works , but i need to use slice since i have no idea how many tags there might be, any suggestion for this problem?

This is what table looks like

1 | {"tags": ["asd", "dsa"], "title": "First Title"}
2 | {"tags": ["tsa", "asd"], "title": "Second Title"}
3 | {"tags": ["qwe", "asd"], "title": "Third Title"}
Seth
  • 31
  • 4

0 Answers0