Home >Backend Development >Golang >How Can I Successfully Unmarshal JSON Data with Spaces in Keys Using Go's `encoding/json`?

How Can I Successfully Unmarshal JSON Data with Spaces in Keys Using Go's `encoding/json`?

Susan Sarandon
Susan SarandonOriginal
2024-12-23 22:50:12836browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn