encoding/json: how to unmarshal an int64 array

2,152 views
Skip to first unread message

sleepy

unread,
May 9, 2016, 4:48:12 AM5/9/16
to golang-nuts
I need to decode below input

{ A:  ["1", "2", "3", "3333333333333333211"] }

into below struct

type foo struct {
  A
[]int64 `json:",string"`
}

but got below error message

json: cannot unmarshal string into Go value of type int64

how could I decode it correctly? Thanks. 

Jakob Borg

unread,
May 9, 2016, 5:11:10 AM5/9/16
to sleepy, golang-nuts
One way is to use a custom unmarshaller that goes via a json.Number:

https://play.golang.org/p/gHEj8WHuTx

//jb
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Matt Harden

unread,
May 9, 2016, 12:23:56 PM5/9/16
to Jakob Borg, sleepy, golang-nuts
I find it interesting that Jakob's solution worked. I think that actually shows a bug Unmarshal: a json.Number is supposed to represent a JSON numeric literal, but here we see it decoding a JSON string instead, and without the ",string" tag!

Regarding the original question, the ",string" tag doesn't work there because the string option "applies only to fields of string, floating point, integer, or boolean types," and []int64 is a slice of integers, not an integer itself.

Here's a solution that doesn't rely on the difference between encoding and decoding json.Number, unfortunately you have to change the type of integer in the slice for it to work; you could then copy the values over to an []int64 slice using a loop if that's required:

sleepy

unread,
May 9, 2016, 10:02:50 PM5/9/16
to golang-nuts, ja...@nym.se, zhang...@gmail.com
thanks for the solution.
I think it would be good if 'string' tag could also be applied to slices, and raised an enhancement request to the project.

在 2016年5月10日星期二 UTC+8上午12:23:56,Matt Harden写道:
Reply all
Reply to author
Forward
0 new messages