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

How Can I Unmarshal JSON with Spaces in Key Names Using Go's `encoding/json`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-25 07:57:10516browse

How Can I Unmarshal JSON with Spaces in Key Names Using Go's `encoding/json`?

JSON Key Names with Spaces: Unmarshalling Made Possible

Deserializing JSON data with complex keys that contain spaces can often pose challenges during unmarshalling. Let's investigate a specific example using the encoding/json library in Go.

Problem:

Consider the following JSON schema:

[
  {"Na me": "Platypus", "Order": "Monotremata"},
  {"Na me": "Quoll", "Order": "Dasyuromorphia"}
]

Using the standard encoding/json library to unmarshal this data into the following Go struct:

type Animal struct {
    Name  string `json:"Na me"`
    Order string `json:"Order,omitempty"`
}

results in an empty "Name" field due to the space in the JSON key.

Cause:

The space in the JSON key confuses the unmarshalling process. The library tries to match the key "Na me" with a field in the Animal struct, but there is no corresponding field.

Solution:

To resolve this issue, ensure that the struct field tags in the json tag specify the correct key names, including the spaces:

type Animal struct {
    Name  string `json:"Na me"`
    Order string `json:"Order,omitempty"`
}

With this revised tagging, the unmarshalling process can successfully map the JSON keys to the correct struct fields, resulting in the expected output:

[
  {Name:Platypus Order:Monotremata}
  {Name:Quoll Order:Dasyuromorphia}
]

The above is the detailed content of How Can I Unmarshal JSON with Spaces in Key Names 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