Get field name that err's in Go json unmarshal


I have some big json files that are slightly different in the types that the fields contain.

{ "a":"1" }


{ "a":1 }

When I unmarshal the second I get:

cannot unmarshal number into Go value of type string

However since these jsons are large I would like to have the actual field that is in error so I can fix them. The UnmarshalTypeError does not hold the Struct’s field type.

Does anybody know of a way to get to field name? (not debugging I have a lot of different fields that err)

I know how to solve the type conversion. What I need is a method to see what fields I need to apply that conversion to.


The short answer is that you can’t.

However, to fix your problem, there is multiple solutions:

  • Dive into the json.Unmarshal source code to change its working and add the information you need: copy the function to a local package, do your edits, and use this function
  • Use a thrid-party tool to help you, for example a JSON validator compatible with JSON Schema: here is an online example, there is probably some better-suited tool

Answered By – Elwinar

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.