Junior — Middle
Have you worked with the jsonb data type in a database?
sobes.tech AI
Answer from AI
Yes, the jsonb data type in PostgreSQL is a binary representation of JSON that allows efficient storage and indexing of JSON data.
In Go, working with jsonb typically involves using the database/sql package along with a PostgreSQL driver (such as lib/pq or pgx). To pass and retrieve data in a jsonb field, types like []byte or string are used, as well as structures that are serialized/deserialized using the encoding/json package.
Example of writing a structure to a jsonb field:
import (
"database/sql"
"encoding/json"
_ "github.com/lib/pq"
)
type Data struct {
Name string `json:"name"`
Age int `json:"age"`
}
func insertJSONB(db *sql.DB, d Data) error {
jsonData, err := json.Marshal(d)
if err != nil {
return err
}
_, err = db.Exec("INSERT INTO table_name (jsonb_column) VALUES ($1)", jsonData)
return err
}
Thus, working with jsonb involves serializing structures into JSON, storing them in a jsonb field, and then querying and deserializing them.