Home > Article > Backend Development > How to correctly parse JSON data in Golang?
Parsing JSON data in Golang can be done through the following steps: Use the encoding/json package. Use json.Marshal() to convert the data structure into JSON byte slices. Use json.Unmarshal() to parse JSON data.
How to correctly parse JSON data in Golang
In Golang, parsing JSON data is a common task. Here are the steps on how to correctly parse JSON data:
1. Use the encoding/json
package
Golang provides encoding/json
Built-in package to handle JSON data.
2. Marshal JSON data
If you have any type of data structure, you can use the json.Marshal()
function to convert it to JSON byte slice:
import "encoding/json" type Person struct { Name string Age int } p := Person{"Alice", 25} data, err := json.Marshal(p) if err != nil { // 处理错误 }
3. Unmarshal JSON data
To parse JSON data, you can use the json.Unmarshal()
function:
import "encoding/json" type Person struct { Name string Age int } var data []byte // JSON 字节切片 var p Person err := json.Unmarshal(data, &p) if err != nil { // 处理错误 }
Practical case
Suppose you have a JSON file containing user information:
{ "users": [ { "name": "Alice", "age": 25 }, { "name": "Bob", "age": 30 } ] }
To parse this file, you can follow these steps:
import "io/ioutil" data, err := ioutil.ReadFile("users.json") if err != nil { // 处理错误 }
import "encoding/json" type User struct { Name string Age int } var users []User err := json.Unmarshal(data, &users) if err != nil { // 处理错误 }
users
A single user object in the slice. The above is the detailed content of How to correctly parse JSON data in Golang?. For more information, please follow other related articles on the PHP Chinese website!