How can I parse a string that represents a JSON array in Go using the encoding/json package?
type JsonType struct { Array []string } func main() { dataJson := `["1","2","3"]` arr := JsonType{} unmarshaled := json.Unmarshal([]byte(dataJson), &arr.Array) log.Printf("Unmarshaled: %v", unmarshaled) }
The provided code returns the error value from Unmarshal. To correctly parse the JSON array, use the following code:
err := json.Unmarshal([]byte(dataJson), &arr)
Additionally, you can simplify the code by using a slice instead of a custom struct:
package main import ( "encoding/json" "fmt" ) func main() { dataJson := `["1","2","3"]` var arr []string err := json.Unmarshal([]byte(dataJson), &arr) fmt.Println(err) fmt.Println(arr) }
This code will output:
<nil> [1 2 3]
Passing a pointer to Unmarshal enables the function to reduce or eliminate memory allocations. Additionally, in a processing context, the caller may reuse the same value repeatedly, further saving allocations.
The above is the detailed content of How to Parse JSON Arrays in Go using the `encoding/json` Package?. For more information, please follow other related articles on the PHP Chinese website!