Standard library / encoding/json

Validate a single JSON document

A Decoder.Decode call reads only one JSON value. To require a single document, decode the intended value and then require io.EOF from a second decode; bound untrusted input separately. Expected stdout: 'false\n'.

Formal Syntax & Structure

go syntaxgo
Decode(&value); Decode(&extra) == io.EOF

Working Example

Example Snippetgo
package main
import (  "encoding/json"  "fmt"  "io"  "strings")
func must(e error) {  if e != nil {    panic(e)  }}
func main() {  d := json.NewDecoder(strings.NewReader("1 2"))  var n int  must(d.Decode(&n))  var extra any  fmt.Println(d.Decode(&extra) == io.EOF)}
Go Reference