RickyA
RickyA

Reputation: 16029

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" }

vs.

{ "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)

[EDIT] 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.

Upvotes: 6

Views: 2414

Answers (2)

natschz
natschz

Reputation: 1117

Now the UnmarshalTypeError, contains the field name.

Upvotes: 2

Elwinar
Elwinar

Reputation: 9509

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

Upvotes: 3

Related Questions