Home > Article > Backend Development > How to retrieve JSON data from database in Golang?
Retrieving JSON data from the database in Golang can be done through the following steps: use the sql.RawBytes type to store JSON data; execute a query and scan the data into the sql.RawBytes variable; use the json.Unmarshal function to deserialize the JSON data.
How to retrieve JSON data from database in Golang
In Golang, you can use sql.RawBytes type to store and retrieve JSON data. This approach allows you to store JSON data as binary data in the database and then deserialize it into a JSON object upon retrieval.
Here are the steps on how to retrieve JSON data from database in Golang:
1. Install necessary libraries
import ( "database/sql" _ "github.com/go-sql-driver/mysql" // 数据库驱动程序(根据需要更改) "encoding/json" )
2. Open a database connection
db, err := sql.Open("mysql", "user:password@tcp(host:port)/database") if err != nil { // 处理错误 }
3. Execute the query
To retrieve JSON data from the database, use the sql.RawBytes
type.
rows, err := db.Query("SELECT json_column FROM table_name") if err != nil { // 处理错误 }
4. Scan rows
For each row of the query, use the Scan
method to scan the json_column
column tosql.RawBytes
type variable.
var jsonBytes []byte err = rows.Scan(&jsonBytes) if err != nil { // 处理错误 }
5. Deserializing JSON data
To deserialize binary JSON data into a JSON object, use the json.Unmarshal
function .
var jsonObject map[string]interface{} err = json.Unmarshal(jsonBytes, &jsonObject) if err != nil { // 处理错误 }
Practical case
Suppose you have a table named users
, which has a table named json_data
JSON
columns. To retrieve the json_data
column from the users
table:
rows, err := db.Query("SELECT json_data FROM users") if err != nil { // 处理错误 } for rows.Next() { var jsonBytes []byte err = rows.Scan(&jsonBytes) if err != nil { // 处理错误 } var jsonObject map[string]interface{} err = json.Unmarshal(jsonBytes, &jsonObject) if err != nil { // 处理错误 } fmt.Println(jsonObject) }
The above code will iterate through each row in the users
table and replace the json_data
Deserialize the column into a JSON object and print it to the console.
The above is the detailed content of How to retrieve JSON data from database in Golang?. For more information, please follow other related articles on the PHP Chinese website!