Home  >  Article  >  Backend Development  >  How to parse JSON data from HTTP response in Golang?

How to parse JSON data from HTTP response in Golang?

WBOY
WBOYOriginal
2024-06-03 13:26:57384browse

Parsing JSON responses in Go: Use the Unmarshal function of the encoding/json package. Create a target structure that represents JSON data. Read the HTTP response body and parse the JSON data. Print or use the parsed data.

如何在 Golang 中从 HTTP 响应中解析 JSON 数据?

How to parse JSON data from HTTP response in Golang

In Golang, you can use encoding/ The json package parses JSON data in HTTP responses. This package provides an Unmarshal function that decodes JSON-encoded data into a target structure.

Code example:

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {
    // 创建一个 HTTP 客户端
    client := &http.Client{}

    // 发送一个 GET 请求
    resp, err := client.Get("https://example.com/api/data")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()

    // 读取响应体
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(err)
        return
    }

    // 创建一个目标结构
    type Data struct {
        Name string
        Age  int
    }
    var data Data

    // 解析 JSON 数据
    if err := json.Unmarshal(body, &data); err != nil {
        fmt.Println(err)
        return
    }

    // 打印解析后的数据
    fmt.Println(data)
}

Practical case:

This example is from a sample API (https:/ /example.com/api/data) and parse it into a Data structure. Then, it prints the parsed data.

You can do this by using your favorite IDE or text editor to create a new file (e.g. main.go) and paste the code above. You can then run the following commands to compile and execute the program:

go run main.go

This will output the parsed JSON data.

The above is the detailed content of How to parse JSON data from HTTP response 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