实现说明
先 json.Valid 校验再解码以函数 main为骨架。
使用要点
- 跑完文件,输出里会留下标记——
good:、broken:、would decode broken。
常见问题
运行「先 json.Valid 校验再解码」会打印什么?
运行文件本身,good:、broken:、would decode broken 这些前缀各对应一段演示逻辑。
核心语句
broken := []byte(`{"id":7,}`) // a trailing comma is not valid JSON
代码示例
package main
import (
"encoding/json"
"fmt"
)
func main() {
good := []byte(`{"id":7,"tags":["a","b"]}`)
broken := []byte(`{"id":7,}`) // a trailing comma is not valid JSON
// json.Valid is a syntax check only: nothing is decoded and no target struct is allocated
fmt.Println("good:", json.Valid(good))
fmt.Println("broken:", json.Valid(broken))
// Valid first, Unmarshal second: bad data takes the explicit rejection path
if json.Valid(broken) {
fmt.Println("would decode broken")
} else {
fmt.Println("rejected before decode")
}
// Input with leading whitespace also passes: whitespace is legal syntax
fmt.Println("spaces:", json.Valid([]byte(" [1, 2]")))
}