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
Release: 2024-12-25 07:57:10
Original
516 people have browsed it

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"}
]
Copy after login

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"`
}
Copy after login
Copy after login

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"`
}
Copy after login
Copy after login

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}
]
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template