Home >Backend Development >Golang >Why Does JSON Unmarshaling an Array into a Go Struct Cause a Panic?

Why Does JSON Unmarshaling an Array into a Go Struct Cause a Panic?

Linda Hamilton
Linda HamiltonOriginal
2024-12-16 10:49:10784browse

Why Does JSON Unmarshaling an Array into a Go Struct Cause a Panic?

Panic: JSON Unmarshal Array into Go Struct

When attempting to parse data from a JSON API, you encountered the error: "panic: json: cannot unmarshal array into Go value of type main.Structure." The issue arises when unmarshalling a JSON array into a Go struct.

Your Code:

type Structure struct {
        stuff []interface{}
}

func main() {
        // ...

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

Expected Result:

You expected the code to return a list of interface objects.

Actual Result:

Instead, you received an error indicating that the JSON array could not be unmarshalled into the Structure Go value.

Solution:

To resolve this issue, consider two approaches:

  1. Unmarshal to a Slice:

    Replace the line:

    decoded := &Structure{}

    with:

    var data []interface{}

    This will unmarshal the JSON array to a slice of interfaces.

  2. Unmarshal to a Slice of Structs:

    Create specific structs for the response data structure. For example:

    type Tick struct {
      ID string
      Name string
      Symbol string
      Rank string
      Price_USD string
    }

    Then, unmarshal to a slice of these structs:

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

The above is the detailed content of Why Does JSON Unmarshaling an Array into a Go Struct Cause a Panic?. 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