Home > Article > Backend Development > Use json.Decoder in golang to decode JSON files into structures
Use json.Decoder in golang to decode JSON files into structures
JSON (JavaScript Object Notation) is a commonly used data exchange format, which has simplicity , easy to read and easy to parse. In golang, you can use json.Decoder to decode JSON files into structures.
In golang, you first need to define a structure, and the fields of the structure need to correspond to the keys in the JSON file. Next, we can use json.Decoder to implement the decoding process. The following is a code example using "people.json" as an example:
package main import ( "encoding/json" "fmt" "os" ) type Person struct { Name string `json:"name"` Age int `json:"age"` Country string `json:"country"` } func main() { // 打开JSON文件 file, err := os.Open("people.json") if err != nil { fmt.Println("打开文件失败,错误信息:", err) return } defer file.Close() // 创建Decoder decoder := json.NewDecoder(file) // 解码json到结构体 var people []Person err = decoder.Decode(&people) if err != nil { fmt.Println("解码失败,错误信息:", err) return } // 打印解码结果 for _, p := range people { fmt.Println("姓名:", p.Name) fmt.Println("年龄:", p.Age) fmt.Println("国家:", p.Country) fmt.Println("------------------") } }
In the above code, we first define a Person structure, the fields of which are the same as those in the "people.json" file corresponding to the key. Create a json.Decoder object by calling the json.NewDecoder function, which can read JSON data from the file and decode it. We then use the decoder.Decode method to decode the JSON data into a people slice.
Finally, we loop through the people slice and print out each person’s name, age, and country.
You can define the corresponding structure based on the actual JSON file structure before writing code to ensure the accuracy of decoding. Also, be careful to handle errors appropriately to avoid program crashes or unpredictable results.
Hope the above code example can help you understand how to use json.Decoder in golang to decode JSON files into structures.
The above is the detailed content of Use json.Decoder in golang to decode JSON files into structures. For more information, please follow other related articles on the PHP Chinese website!