获取在Go的JSON解组中出错的字段名。

huangapple go评论83阅读模式
英文:

Get field name that err's in Go json unmarshal

问题

我有一些大的 JSON 文件,这些文件在字段包含的类型上略有不同。

{ "a":"1" }

{ "a":1 }

当我解组第二个 JSON 时,会出现以下错误:

无法将数字解组为 Go 类型为字符串的值

然而,由于这些 JSON 文件很大,我希望能够找到实际出错的字段,以便我可以修复它们。UnmarshalTypeError 并不包含结构体的字段类型。

有人知道如何获取字段名的方法吗?(不是调试,因为我有很多不同的字段出错)

[编辑]
我知道如何解决类型转换的问题。我需要的是一种方法来查看我需要对哪些字段应用该转换。

英文:

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.

答案1

得分: 3

简短的回答是你不能。

然而,为了解决你的问题,有多种解决方案:

  • 深入研究json.Unmarshal的源代码,修改其工作方式并添加你需要的信息:将该函数复制到一个本地包中,进行编辑,然后使用这个函数。
  • 使用第三方工具来帮助你,例如与JSON Schema兼容的JSON验证器:这里有一个在线示例,可能还有一些更适合的工具。
英文:

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

答案2

得分: 1

现在的UnmarshalTypeError中包含了字段名。

英文:

Now the UnmarshalTypeError, contains the field name.

huangapple
  • 本文由 发表于 2014年6月20日 18:29:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/24325210.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定