json: cannot unmarshal array into Go value of type main error

4,320 views
Skip to first unread message

Rejoy

unread,
Feb 2, 2017, 6:20:49 PM2/2/17
to golang-nuts

I 'd like to unmarshal database records into a struct type. I get the error "json: cannot unmarshal array into Go value of type main..".

Working example https://play.golang.org/p/keY-3z7lyA
 
I can unmarshal the data to []map[String]string, but cannot reference it using key value pairs in the template.

The snippet for code in the template:
     <div class="container">
     {{ range $key, $value := . }}
        <li><strong>{{ $key }}</strong>: {{ $value }}</li>
    {{ end }}
    </div>

The output that I get on the webserver:

  • 0: map[quantity:100 image:1Appleiphone7.jpeg pname:iphone7 price:70000 puid:d6742e4e-2ad6-43c5-97f4-e8a7b00684e2]
  • 1: map[image:2SamsungGalaxys7.jpeg pname:SamsungGalaxy7 price:70000 puid:12d3d8fc-66b6-45f9-a91b-d400b91c32aa quantity:100]



I wanted to display the data as a table by ranging over the key-value pairs. But am not able to figure out how.


Dan Kortschak

unread,
Feb 2, 2017, 6:41:13 PM2/2/17
to Rejoy, golang-nuts
You have handed json.Unmarshal a non-slice/non-array type.

Try this https://play.golang.org/p/Zl5G_Rkt26

On Thu, 2017-02-02 at 15:15 -0800, Rejoy wrote:
> I 'd like to unmarshal database records into a struct type. I get the
> error "json: 
> cannot unmarshal array into Go value of type main..".
>
> Working example https://play.golang.org/p/keY-3z7lyA
>  
> I can unmarshal the data to []map[String]string, but cannot reference
> it 
> using key value pairs in the template.
>
> The snippet for code in the template:
>      <div class="container">
>      {{ range $key, $value := . }} 
>         <li><strong>{{ $key }}</strong>: {{ $value }}</li> 
>     {{ end }} 
>     </div>
>
> The output that I get on the webserver:
>
> - *0*: map[quantity:100 image:1Appleiphone7.jpeg pname:iphone7
> price:70000 
> puid:d6742e4e-2ad6-43c5-97f4-e8a7b00684e2] 
> - *1*: map[image:2SamsungGalaxys7.jpeg pname:SamsungGalaxy7

Kevin Powick

unread,
Feb 6, 2017, 8:11:09 PM2/6/17
to golang-nuts

Since you have an array of JSON data, you need to Unmarshal it into an Array of your struct, then range over the resulting array of your struct.

Updated version of your code at: https://play.golang.org/p/gnx7pjTzOT

--
Kevin Powick

Kevin Powick

unread,
Feb 6, 2017, 8:12:40 PM2/6/17
to golang-nuts

Oops.  I didn't see this correct answer posted by Kortschak

--
Kevin Powick
Reply all
Reply to author
Forward
0 new messages