Parsing JSON Arrays in Go with the JSON Package
Problem: How can you parse a JSON string representing an array in Go using the json package?
Code Example:
Consider the following Go code:
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) }
Explanation:
The provided code defines a type JsonType with an array of strings. It then attempts to unmarshal a JSON string into the array field of a JsonType instance. However, there is an issue with the code.
Solution:
The return value of Unmarshal is an error. The code originally printed this error instead of the unmarshaled array. To fix it, you can change the code to:
err := json.Unmarshal([]byte(dataJson), &arr)
Additionally, you can simplify the code by directly unmarshaling into the array slice without using a custom type:
var arr []string _ = json.Unmarshal([]byte(dataJson), &arr)
This code assigns the unmarshaled slice to arr. The underscore before the assignment suppresses the error value, which is not used in this code.
By using the json package effectively, you can easily parse JSON arrays in Go.
Haftungsausschluss: Alle bereitgestellten Ressourcen stammen teilweise aus dem Internet. Wenn eine Verletzung Ihres Urheberrechts oder anderer Rechte und Interessen vorliegt, erläutern Sie bitte die detaillierten Gründe und legen Sie einen Nachweis des Urheberrechts oder Ihrer Rechte und Interessen vor und senden Sie ihn dann an die E-Mail-Adresse: [email protected] Wir werden die Angelegenheit so schnell wie möglich für Sie erledigen.
Copyright© 2022 湘ICP备2022001581号-3