Home >Backend Development >Golang >How to Parse JSON Arrays into Structured Data in Go?
Using Unmarshal with Defined Struct
Problem:
How to parse a complex JSON array containing objects into a structured format in Go?
Sample JSON:
[{"id":694476444991229955,"id_str":"694476444991229955"}]
Solution:
Define a Go struct to model the JSON data.
type Tweet struct { ID int64 `json:"id"` IDStr string `json:"id_str"` }
Create a slice of the tweet struct to hold the parsed results.
tweets := make([]Tweet, 0)
Unmarshal the JSON array into the tweet slice.
err := json.Unmarshal([]byte(jsonString), &tweets) if err != nil { fmt.Println(err) }
Iterate over the tweet slice to access the parsed data.
for _, tweet := range tweets { fmt.Println(tweet.ID, tweet.IDStr) }
Unmarshaling into Map[string]interface{} slice
Note: This method requires indexing and type assertion to access the values.
Create a slice of maps to hold the parsed results.
tweets := make([]map[string]interface{}, 0)
Unmarshal the JSON array into the map slice.
err := json.Unmarshal([]byte(jsonString), &tweets) if err != nil { fmt.Println(err) }
Iterate over the map slice to access the parsed data.
for _, tweet := range tweets { id, ok := tweet["id"].(int64) if ok { fmt.Println("ID:", id) } }
The above is the detailed content of How to Parse JSON Arrays into Structured Data in Go?. For more information, please follow other related articles on the PHP Chinese website!