← 中文资源

简体中文版本

先 json.Valid 校验再解码

json.Valid 只做语法检查不解码:尾逗号这类坏输入在解码前就被拒绝,避免 Unmarshal 半途报错留下半填充结构;前导空白属于合法语法,同样通过。

阅读英文原文

实现说明

先 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]")))
}