In modern Web technology, JSON has become the mainstream data format. The json package in the Go language provides a series of functions and structures for JSON encoding and decoding, making using JSON very convenient. This article will introduce how to use JSON to make requests in the Go language.
The Go language provides many ways to send HTTP requests and process JSON responses. Here we introduce a common way:
import ( "encoding/json" "fmt" "net/http" "os" )
type User struct { Name string `json:"name"` Age int `json:"age"` Email string `json:"email"` }
func main() { url := "https://jsonplaceholder.typicode.com/users" // 请求地址 // 发送HTTP GET请求 response, err := http.Get(url) if err != nil { fmt.Println("请求失败:", err) os.Exit(1) } defer response.Body.Close() // 将JSON响应解码到结构体 var users []User err = json.NewDecoder(response.Body).Decode(&users) if err != nil { fmt.Println("解码失败:", err) os.Exit(1) } // 显示解码后的结构体 for _, user := range users { fmt.Printf("姓名:%s,年龄:%d,邮箱:%s\n", user.Name, user.Age, user.Email) } }
The above code will send an HTTP GET request to the specified URL and decode the response into a slice of User structure. You can modify it according to your needs.
To sum up, using JSON to make requests is a very common operation in Golang. Hope this article is helpful to you.
The above is the detailed content of Let's talk about how to use JSON to make requests in Go language. For more information, please follow other related articles on the PHP Chinese website!