Home >Backend Development >Golang >How to convert JSON data to structure in Golang?
In Golang, JSON data can be converted into a structure through the following steps: define a structure with field names that match the JSON attribute names, and use the json tag to specify the JSON field names. Use the json.Unmarshal function from the encoding/json package to parse a JSON string and convert it into a pointer to a structure. Check for parsing errors. Access structure fields to extract data.
How to convert JSON data into a structure in Golang
Introduction
Golang provides the encoding/json
package to easily process JSON data. It allows you to convert JSON data into structures, making it easy to access and manipulate JSON data.
Practical case
Suppose you have a JSON string:
{ "name": "John Doe", "age": 30, "occupation": "Software Engineer" }
and want to convert it into a structure. Here are the steps:
type Person struct { Name string `json:"name"` Age int `json:"age"` Occupation string `json:"occupation"` }
struct
keyword creates a new Structure type. json
tag specifies the JSON field name. import "encoding/json" var jsonStr = `{ "name": "John Doe", "age": 30, "occupation": "Software Engineer" }` var person Person err := json.Unmarshal([]byte(jsonStr), &person) if err != nil { // 处理错误 }
json.Unmarshal
The function parses the JSON string and Convert it to a pointer to a structure. jsonStr
is a JSON string. person
is the target structure. Unmarshal
will return that error. fmt.Println(person.Name) // "John Doe" fmt.Println(person.Age) // 30 fmt.Println(person.Occupation) // "Software Engineer"
Note
json
tag. Unmarshal
. The above is the detailed content of How to convert JSON data to structure in Golang?. For more information, please follow other related articles on the PHP Chinese website!