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
Mary-Kate OlsenOriginal
2024-11-30 09:12:17968browse

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)

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)
  • Unmarshal into a Slice of Structs:
type Tick struct {
     ID string
     Name string
     ... and so on
}

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

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!

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