JSON Valid Gates Decoding Early

Validate JSON syntax with json.Valid before decoding: trailing commas fail the gate, so bad payloads are rejected without half-filled structs.

GoResilience

Code

gosnippet
25 lines
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]")))
}

The mechanics

Every runnable line is contained in the function main.

Caveats

  • Nothing to install: the snippet stays inside the standard library.

Applying it

The main signature is written as func main()

The file’s output announces each step as it happens: good:, broken:, would decode broken.

Statements that matter

broken := []byte(`{"id":7,}`) // a trailing comma is not valid JSON

Interactive Tools for This Topic

FAQ

What does JSON Valid Gates Decoding Early print when run?
Invoke the file as-is — the `good:`, `broken:`, `would decode broken` prefixes identify which step printed each line.