为什么 JSON 解析不会因传递给 Decode() 的完全不同的类型而失败?
Why doesn't JSON parsing fail with completely different type passed to Decode()?
我想从 API 解析以下数据结构:
type OrderBook struct {
Pair string `json:"pair"`
UpdateTime int64 `json:"update_time"`
}
type depthResponse struct {
Result OrderBook `json:"result"`
// doesn't matter here
//Cmd string `json:"-"`
}
当我解析以下内容时:
data := `{"error":{"code":"3016","msg":"交易对错误"},"cmd":"depth"}`
它不会失败。为什么?
完整源代码(playground)
package main
import (
"encoding/json"
"fmt"
"log"
"strings"
)
type OrderBook struct {
Pair string `json:"pair"`
UpdateTime int64 `json:"update_time"`
}
type depthResponse struct {
Result OrderBook `json:"result"`
}
func main() {
data := `{"error":{"code":"3016","msg":"交易对错误"},"cmd":"depth"}`
r := strings.NewReader(data)
var resp depthResponse
if err := json.NewDecoder(r).Decode(&resp); err != nil {
log.Fatalf("We should end up here: %v", err)
}
fmt.Printf("%+v\n", resp)
}
这是 Decode
的预期行为(如 Unmarshal
函数中所述):
https://golang.org/pkg/encoding/json/#Unmarshal
By default, object keys which don't have a corresponding struct field are ignored.
但是,如果输入 JSON 的字段未包含在目标结构中,您可以使用 DisallowUnknownFields()
函数(也如文档中所述)使其失败。
dec := json.NewDecoder(r)
dec.DisallowUnknownFields()
在这种情况下,您会收到预期的错误消息。
我想从 API 解析以下数据结构:
type OrderBook struct {
Pair string `json:"pair"`
UpdateTime int64 `json:"update_time"`
}
type depthResponse struct {
Result OrderBook `json:"result"`
// doesn't matter here
//Cmd string `json:"-"`
}
当我解析以下内容时:
data := `{"error":{"code":"3016","msg":"交易对错误"},"cmd":"depth"}`
它不会失败。为什么?
完整源代码(playground)
package main
import (
"encoding/json"
"fmt"
"log"
"strings"
)
type OrderBook struct {
Pair string `json:"pair"`
UpdateTime int64 `json:"update_time"`
}
type depthResponse struct {
Result OrderBook `json:"result"`
}
func main() {
data := `{"error":{"code":"3016","msg":"交易对错误"},"cmd":"depth"}`
r := strings.NewReader(data)
var resp depthResponse
if err := json.NewDecoder(r).Decode(&resp); err != nil {
log.Fatalf("We should end up here: %v", err)
}
fmt.Printf("%+v\n", resp)
}
这是 Decode
的预期行为(如 Unmarshal
函数中所述):
https://golang.org/pkg/encoding/json/#Unmarshal
By default, object keys which don't have a corresponding struct field are ignored.
但是,如果输入 JSON 的字段未包含在目标结构中,您可以使用 DisallowUnknownFields()
函数(也如文档中所述)使其失败。
dec := json.NewDecoder(r)
dec.DisallowUnknownFields()
在这种情况下,您会收到预期的错误消息。