Home > Backend Development > Golang > Why Does JSON Unmarshal Fail When Mapping Arrays to Go Structs?

Why Does JSON Unmarshal Fail When Mapping Arrays to Go Structs?

Mary-Kate Olsen
Release: 2024-11-30 09:12:17
Original
966 people have browsed it

Why Does JSON Unmarshal Fail When Mapping Arrays to Go Structs?

Unable to Unmarshal JSON Array into Go Structure

In an attempt to parse data from a JSON API, a programmer encountered the error: "panic: json: cannot unmarshal array into Go value of type main.Structure."

Problem Excerpt:

type Structure struct {
        stuff []interface{}
}

...

decoded := &Structure{}
err = json.Unmarshal(body, decoded)
Copy after login

Expected Result:

A list of interface objects.

Actual Result:

panic: json: cannot unmarshal array into Go value of type main.Structure

Solution:

The issue arises when trying to unmarshal a JSON array into a Go struct. To resolve this, one can either:

  • Unmarshal into a Slice:
var data []interface{}
err = json.Unmarshal(body, &data)
Copy after login
  • Unmarshal into a Slice of Structs:
type Tick struct {
     ID string
     Name string
     ... and so on
}

var data []Tick
err = json.Unmarshal(body, &data)
Copy after login

By customizing the struct type to match the structure of the response data, the unmarshaling process will successfully parse the JSON array.

The above is the detailed content of Why Does JSON Unmarshal Fail When Mapping Arrays to Go Structs?. 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