import ( "encoding/json" "os" ) type Person struct { Name string Age int } func main() { var p Person jsonStr := `{"Name": "Alice", "Age": 25}` dec := json.NewDecoder(strings.NewReader(jsonStr)) for { t, err := dec.Token() if err == io.EOF { break } if err != nil { log.Fatal(err) } if tok, ok := t.(json.Delim); ok && tok == '{' { err = dec.Decode(&p) if err != nil { log.Fatal(err) } break } } fmt.Println(p.Name, p.Age) // prints "Alice 25" }
import ( "encoding/json" "fmt" "strings" ) func main() { jsonStr := `{"numbers": [1, 2, 3, {"name": "Alice", "age": 25}]}` dec := json.NewDecoder(strings.NewReader(jsonStr)) for { t, err := dec.Token() if err == io.EOF { break } if err != nil { log.Fatal(err) } if tok, ok := t.(json.Delim); ok && tok == '[' { for dec.More() { t, err := dec.Token() if err != nil { log.Fatal(err) } switch t := t.(type) { case float64: fmt.Printf("got number: %v\n", t) case json.Delim: if t == '{' { var m map[string]interface{} err := dec.Decode(&m) if err != nil { log.Fatal(err) } fmt.Printf("got object: %+v\n", m) } } } break } } }In this example, the Token method is called to extract the numbers array, which contains nested objects. The More method is called to check if any more tokens are available in the array. The switch statement differentiates between number values and JSON objects and acts accordingly. The Go package library of the encoding/json Decoder Token is the "encoding/json" package.