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
Release: 2024-12-16 10:49:10
Original
786 people have browsed it

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

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

    with:

    var data []interface{}
    Copy after login

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

    Then, unmarshal to a slice of these structs:

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

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!

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