Home >Backend Development >Golang >How Can I Successfully Unmarshal JSON Data with Spaces in Keys Using Go's `encoding/json`?
Spaces in JSON Keys: Overcoming the Unmarshaling Obstacle
Unmarshaling JSON data with keys containing spaces can pose a challenge for the standard encoding/json library in Go. By default, the library will try to match JSON keys to the field names without spaces. In the provided code:
type Animal struct { Name string `json:"Na me"` Order string `json:"Order,omitempty"` }
The Name key in the JSON data conflicts with this pattern. This error can be remedied by modifying the json tags to accurately reflect the JSON keys:
type Animal struct { Name string `json:"Na me"` // Corrected the space after the colon Order string `json:"Order,omitempty"` }
As the documentation for encoding/json states, spaces are not allowed in json tags after the colon. By following this guidance, the unmarshaling process will be able to correctly identify and map the JSON keys to the corresponding fields in the Animal struct. Executing the corrected code will yield the expected output:
[{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
The above is the detailed content of How Can I Successfully Unmarshal JSON Data with Spaces in Keys Using Go's `encoding/json`?. For more information, please follow other related articles on the PHP Chinese website!