In Golang, use the encoding/json package to convert the structure into JSON data. The steps are as follows: Install the encoding/json package. Define the structure. Convert the structure to a JSON string using the json.Marshal() function.
In Golang, you can use the encoding/json
package to convert structures into JSON data. Here's how to do it:
1. Install the package
go get -u encoding/json
2. Define the structure
type Person struct { Name string Age int }
3 . Convert to JSON
Use the json.Marshal()
function to convert the structure to a JSON string:
import "encoding/json" func main() { person := Person{Name: "John", Age: 30} jsonBytes, err := json.Marshal(person) if err != nil { // 处理错误 } jsonString := string(jsonBytes) fmt.Println(jsonString) }
Output:
{"Name":"John","Age":30}
Practical case: REST API
The following is a practical case showing how to convert a structure into JSON data in a REST API:
import ( "encoding/json" "net/http" "github.com/gorilla/mux" ) type Person struct { Name string Age int } func main() { router := mux.NewRouter() // 路由用于获取单个人的详细信息 router.HandleFunc("/person/{name}", func(w http.ResponseWriter, r *http.Request) { // 从 URL 中获取名称 name := mux.Vars(r)["name"] // 根据名称查询数据库并获取 Person 结构体 person := getPersonFromDB(name) // 将结构体转换为 JSON jsonBytes, err := json.Marshal(person) if err != nil { // 处理错误 } // 将 JSON 发送到客户端 w.Header().Add("Content-Type", "application/json") w.Write(jsonBytes) }) // 启动服务器 http.ListenAndServe(":8080", router) }
In this case , when the client makes a GET request to the /person/{name}
endpoint, the server queries the database, obtains a Person structure, and then converts the structure to JSON and sends it to the client.
The above is the detailed content of How to convert struct to JSON data in Golang?. For more information, please follow other related articles on the PHP Chinese website!