json - Go:获取损坏的 JSON 字段名称

标签 json go

假设我正在将 JSON 输入解析为如下结构:

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

并传递错误数据(string 而不是 int):

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

这是我可以从错误中提取的内容:

// 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)

我还想报告哪个字段是错误的(age,在我的例子中),这可能吗?

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

最佳答案

很遗憾,目前不支持此功能。

有一个accepted issue为了这。实现起来似乎并不容易(请参阅下面的票证中的引述)但希望它与 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.

关于json - Go:获取损坏的 JSON 字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23582744/

相关文章:

javascript - 如何使用 fetch api 从 json 中的先前值获取值?

PHP 不会回显 JSON_ENCODE 除非我回显其他内容

map - 遍历 golang 结构的键和值由于某种原因没有给出相同的结果

Golang 位只使用无符号?

go - 类型开关以通过接口(interface)验证功能

go - 在 Ragel 中使用带有扫描仪 block 的堆栈的正确方法是什么?

javascript - 始终将 JSON 解析为数组

ruby-on-rails - ActionController::UnknownFormat 用于 json 响应

javascript - AngularJS 和 JSON - 添加子对象

go - Go例程AWS lambda