Json UnmarshalTypeError - Which struct field?

2,512 views
Skip to first unread message

bsr

unread,
Mar 9, 2013, 12:22:22 PM3/9/13
to golan...@googlegroups.com
Hello,

I get Json error message as 

json: cannot unmarshal string into Go value of type int

it takes some trial to find which field has a type mismatch, especially if the struct has many fields.

With type switch, I found the exact error was UnmarshalTypeError , but it doesn't has info about which struct field is it.
Is there a way to know which field raised this error.

Thanks.

type UnmarshalTypeError struct {
    Value string       // description of JSON value - "bool", "array", "number -5"
    Type  reflect.Type // type of Go value it could not be assigned to
}

bsr

unread,
Aug 22, 2013, 7:37:03 AM8/22/13
to golan...@googlegroups.com
Hello. I still not sure how to identify which field in my json (bit large in size) causing this error. Any pointers appreciated.

worc...@googlemail.com

unread,
Feb 2, 2015, 11:40:41 AM2/2/15
to golan...@googlegroups.com
Same here! Would be nice to have the error store the line and character number it reached, and the copy of the json body being parsed, so it is possible to inspect exactly which characters in the json could not be parsed.

mike...@appdirect.com

unread,
Feb 1, 2016, 3:16:21 PM2/1/16
to golang-nuts, worc...@googlemail.com
I found this snip useful, its not perfect, but may help.


   beginning := int64(math.Max(float64(0), float64(offsetErr.Offset-20)))
  log.Printf("JSON ERR: %s<--", testJson[beginning:offsetErr.Offset])

Prints something like 
JSON ERR: },
"Database",
"2"<--

C Banning

unread,
Feb 1, 2016, 5:06:00 PM2/1/16
to golang-nuts, worc...@googlemail.com
For Type errors you can resolve the err like this https://play.golang.org/p/OyMsI7oijk and get a little more information to work with.
Reply all
Reply to author
Forward
0 new messages