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
Release: 2024-11-29 01:46:09
Original
911 people have browsed it

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

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

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

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!

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