What is Go lang func NewDecoder(r io.Reader) *Decoder ?

func NewDecoder(r io.Reader) *Decoder is a function defined in the encoding/json package which reads a JSON input stream, stores it in the buffer of a Decoder object, and returns the Decoder object. The Decoder object can then be used to perform methods such as Decode(), More(), InputOutputOffset(), Buffered().

Parameters

r: JSON readable stream that implements a io.Reader interface

Return Value

*Decoder: Object of the type Decoder defined in the encoding/json package

Example

package main
import (
"encoding/json"
"fmt"
"strings"
)
func main() {
const jsonStream = `
{"Name": "Hassan", "Major": "Physics", "RollNumber": 18100026}
`
type Student struct {
Name, Major string
RollNumber int32
}
dec := json.NewDecoder(strings.NewReader(jsonStream))
var stu Student
_ = dec.Decode(&stu)
fmt.Printf("Student Information\nName: %s\t Major: %s\t RollNumber: %d\n", stu.Name, stu.Major, stu.RollNumber)
}

Explanation

In the above example, we define a struct Student with properties Name, Major, and RollNumber. We define jsonStream with a JSON object and pass it to the strings.NewReader() method to make a readable JSON stream. We pass the JSON stream to the func NewDecoder(r io.Reader) *Decoder which returns a Decoder object which is assigned to dec. We use the Decode() method accessible to dec which decodes the JSON object into the properties of Student and store in the stu object.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved