Home > Article > Backend Development > How to read JSON data from file using ioutil in Golang?
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.
#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 }
Practical case:
Suppose we have a file named data.json
file containing the following JSON data:
{ "Name": "John", "Age": 30 }
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
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!