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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.JSON Formatter & ValidatorFormat, beautify, and validate JSON data with configurable indentation. Instantly catches syntax errors and displays a pretty-printed tree structure.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.