How to read JSON data from file using ioutil in Golang?

WBOY
Release: 2024-06-03 11:13:57
Original
588 people have browsed it

To use ioutil to read JSON data from a file in Go, follow these steps: Use ioutil.ReadFile() to read the file contents. Use json.Unmarshal() to decode the byte array into a JSON object. Access the decoded data.

如何在 Golang 中使用 ioutil 从文件读取 JSON 数据?

#How to use ioutil to read JSON data from a file in Go?

The Go language provides the ioutil package for reading and writing files. To read JSON data from a file, you can use the ioutil.ReadFile() function. This function returns a byte array containing the entire contents of the file. We can then use the json.Unmarshal() function to decode the byte array into a JSON object.

Code example:

package main

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

type Data struct {
    Name string
    Age  int
}

func main() {
    // 读取文件内容
    bytes, err := ioutil.ReadFile("data.json")
    if err != nil {
        fmt.Println(err)
        return
    }

    // 将字节数组解码为 JSON 对象
    var data Data
    if err := json.Unmarshal(bytes, &data); err != nil {
        fmt.Println(err)
        return
    }

    // 访问解码后的数据
    fmt.Println(data.Name) // 输出: John
    fmt.Println(data.Age)  // 输出: 30
}
Copy after login

Practical case:

Suppose we have a file named data.json file containing the following JSON data:

{
  "Name": "John",
  "Age": 30
}
Copy after login

We can use the code in the code sample to read and decode this data and then obtain the Name## of the Data object # and Age fields.

Output:

John
30
Copy after login

The above is the detailed content of How to read JSON data from file using ioutil in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!