Home > Article > Backend Development > How to load JSON data from URL in Golang?
In Golang, you can load JSON data from URL by following these steps: Import the necessary packages. Use http.Get to get the response. Close the response body. Read and convert to byte slices. Decode byte slices into JSON data structures.
How to load JSON data from URL in Golang
Loading JSON data in Golang is very simple. Below we introduce how to load JSON data from URL in Golang. The URL loads JSON data and provides a practical case.
Steps:
Import necessary packages:
import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" )
Use http. Get
function gets the response of the data:
resp, err := http.Get("https://example.com/data.json") if err != nil { log.Fatal(err) }
Close the response body in the defer resp.Body.Close()
delay function:
defer resp.Body.Close()
Use ioutil.ReadAll
to read the response body and convert it to a byte slice:
body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) }
Decode the byte slice to JSON data structure:
var data map[string]interface{} if err := json.Unmarshal(body, &data); err != nil { log.Fatal(err) }
Practical case:
The following is a practical case for loading employee data from the JSONPlaceholder API:
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" ) func main() { resp, err := http.Get("https://jsonplaceholder.typicode.com/users") if err != nil { log.Fatal(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) } var users []map[string]interface{} if err := json.Unmarshal(body, &users); err != nil { log.Fatal(err) } for _, user := range users { fmt.Printf("Name: %s, Email: %s\n", user["name"], user["email"]) } }
This case shows how to load a user list and iterate through and print each user's name and email address.
The above is the detailed content of How to load JSON data from URL in Golang?. For more information, please follow other related articles on the PHP Chinese website!