Home  >  Article  >  Backend Development  >  How to load JSON data from URL in Golang?

How to load JSON data from URL in Golang?

WBOY
WBOYOriginal
2024-06-02 11:52:57641browse

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.

如何在 Golang 中从 URL 加载 JSON 数据?

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:

  1. Import necessary packages:

    import (
     "encoding/json"
     "fmt"
     "io/ioutil"
     "log"
     "net/http"
    )
  2. 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)
    }
  3. Close the response body in the defer resp.Body.Close() delay function:

    defer resp.Body.Close()
  4. 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)
    }
  5. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn