Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
json

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

Abdul Monum

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

golang
json

CONTRIBUTOR

Abdul Monum
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring