获取一个损坏的JSON字段名

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

Go: get a broken JSON field name

问题

假设我正在将一个 JSON 输入解析成以下结构:

type Person struct {
    Name string `json:"name"`
    Age  uint   `json:"age"`         
}

并且传入了错误的数据(将 int 误写为 string):

var person Person
err := json.Unmarshal([]byte(`{"name": "Dilbert", "age": "unknown"}`), &person)

这是我从错误中提取的信息:

// 错误信息:无法将字符串解析为类型为 uint 的 Go 值
fmt.Printf("错误信息:%v\n", err) 

// 非预期的值:unknown
jerr := err.(*json.UnmarshalTypeError)
fmt.Printf("非预期的值:%s\n", (*jerr).Value)

// 预期的类型:uint
fmt.Printf("非预期的类型:%v\n", (*jerr).Type)

我想报告哪个字段出错了(在这个例子中是 age),这样可以吗?

(我理解,例如当解析数组或标量值时,这是不适用的,但我仍然希望在对象的情况下可能有一些解决方法或技巧。)

英文:

Suppose I'm parsing a JSON input into a structure like this:

type Person struct {
        Name string `json:"name"`
        Age  uint   `json:"age"`         
}

and pass erroneous data (string instead of int):

var person Person
err := json.Unmarshal([]byte(`{"name": "Dilbert", "age": "unknown"}`), &person)

This is what I can extract from the error:

// Error json: cannot unmarshal string into Go value of type uint
fmt.Printf("Error %v\n", err) 

// Unexpected value: unknown
jerr := err.(*json.UnmarshalTypeError)
fmt.Printf("Unexpected value: %s\n", (*jerr).Value)

// Expected type: uint
fmt.Printf("Unexpected type: %v\n", (*jerr).Type)

I'd like to report also which field is erroneous (age, in my case), is that possible?

(I understand, that, for example, when you parse an array or a scalar value, that's not applicable, but still, I hope there might be some workaround or trick for the case of objects.)

答案1

得分: 5

很抱歉,目前不支持这个功能。

对此有一个已接受的问题1。实现起来似乎并不容易(请参见下面的票据引用),但希望它能随着Go 1.3的到来。

> 由于在生成错误时解码器正在查看字段值本身,而不是包含该字段的结构体,所以实现起来稍微有些不方便。相关代码甚至不知道它正在解码到一个结构体字段中。有几种方法可以解决这个问题,但它们都不是简单的。

英文:

Unfortunately this is currently not supported.

There is an accepted issue for this. It seems to be not trivial to implement (see quote from the ticket below) but hopefully it comes with Go 1.3.

> Made slightly inconvenient to implement because by the time the error
> is generated the decoder is looking at the field value itself, not the
> struct that contains the field. The relevant code doesn't even know
> that it's decoding into a struct field. There are a few ways to get
> around this but they are non-trivial.

huangapple
  • 本文由 发表于 2014年5月10日 23:15:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/23582744.html
匿名

发表评论

匿名网友

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

确定