Home >Backend Development >Golang >How to Fix 'json: cannot unmarshal array into Go value of type main.Structure'?

How to Fix 'json: cannot unmarshal array into Go value of type main.Structure'?

Susan Sarandon
Susan SarandonOriginal
2024-11-29 01:46:09914browse

How to Fix

How to Unmarshal JSON Array into a Go Struct

When trying to parse JSON data from an API, users may encounter the error: "panic: json: cannot unmarshal array into Go value of type main.Structure."

Code Snippet with the Issue

type Structure struct {
     stuff []interface{}
}

... // more code

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

Problem

The root of the issue is the attempt to unmarshal a JSON array into a Go struct.

Solution

Option 1: Unmarshal to a slice

Instead of using a struct, unmarshal the JSON array to a slice of interface{}:

var data []interface{}
err = json.Unmarshal(body, &data)

Option 2: Unmarshal to a slice of structs

If the JSON data has a specific structure, consider creating a slice of structs that match the response data:

type Tick struct {...}
var data []Tick
err = json.Unmarshal(body, &data)

The above is the detailed content of How to Fix 'json: cannot unmarshal array into Go value of type main.Structure'?. 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