Home > Article > Backend Development > How to return json in golang
When developing websites or web applications, it is often necessary to return JSON data in the form of APIs. Therefore, it is crucial to master how to return JSON data in Golang.
This article will introduce Golang’s json package and its basic usage, and how to use it to encode Golang data structures into JSON strings or decode JSON strings into Golang data structures.
In Golang programs, it is very simple to use the json package to operate JSON data. JSON strings can be parsed into Golang variables, and Golang variables can be encoded into JSON strings.
In the Golang program, if you need to encode Golang variables into JSON strings, you can use the json.Marshal() function to complete this task. The following is a sample program that demonstrates how to encode a Go structure into a JSON string:
package main import ( "encoding/json" "fmt" ) type Person struct { Name string Age int } func main() { p := Person{"Tom", 30} b, err := json.Marshal(p) if err != nil { fmt.Println("error:", err) return } fmt.Println(string(b)) }
The output is:
{"Name":"Tom","Age":30}
In the above sample program, the Person structure contains two fields Name and Age. We instantiate it as a variable called p and pass it to the json.Marshal() function. The function will return a byte array of JSON string and an optional error.
If JSON encoding fails, a non-null error will be returned. In the above example, we check for errors and print error messages.
Note: When using json.Marshal() to encode a JSON string, the name of the JSON field is the name of the structure field and must start with a capital letter.
In Golang program, if you need to decode JSON string into Golang variable, you can use the json.Unmarshal() function . The following is a sample program that demonstrates how to decode a JSON string into a Go structure:
package main import ( "encoding/json" "fmt" ) type Person struct { Name string Age int } func main() { jsonStr := `{"Name":"Tom","Age":30}` var p Person err := json.Unmarshal([]byte(jsonStr), &p) if err != nil { fmt.Println("error:", err) return } fmt.Println(p.Name, p.Age) }
The output result is:
Tom 30
In the above sample program, we decode the JSON string with the empty The Person structure is decoded. The JSON string needs to be converted into a byte array, which is modified to accommodate the decoded results. The decoded results will be stored in unmarshaled variables.
A & operator is used here to pass the variable address to the function and use it to modify the actual result.
Similarly, if JSON decoding fails, an error will be returned and the error message will be printed.
In Golang, you can use the net/http package to create an API and return JSON data. The following is a simple sample program that demonstrates how to return JSON data using Golang:
package main import ( "encoding/json" "fmt" "net/http" ) type Person struct { Name string Age int } func main() { http.HandleFunc("/person", handlePerson) http.ListenAndServe(":8080", nil) } func handlePerson(w http.ResponseWriter, r *http.Request) { p := Person{"Tom", 30} b, err := json.Marshal(p) if err != nil { fmt.Println("error:", err) return } w.Header().Set("Content-Type", "application/json") w.Write(b) }
In the above sample program, we created a basic HTTP server, using the net/http package. We use the http.HandleFunc() function to bind the path /person to the handlePerson handler function.
The handlePerson function returns a Person structure with Name and Age fields. It will encode the Person structure into JSON format using the json.Marshal() function. Finally, we use the http.ResponseWriter interface to write the JSON response. Before writing, we use the w.Header().Set() function to set the Content-Type of the response header to application/json.
Now, you know how to encode and decode JSON data using Golang, and how to return JSON data in an HTTP response. Learning these skills will make you more comfortable developing web applications.
The above is the detailed content of How to return json in golang. For more information, please follow other related articles on the PHP Chinese website!