func NewEncoder(w io.Writer) *Encoder
is a function defined in the encoding/json package which gets a JSON encoding of any type
and encodes/writes it any writable stream that implements a io.Writer
interface. The Encoder
object can then be used to perform methods such as Encode()
, SetEscapeHTML()
, Error()
, Unwrap()
.
w
: Writable stream that implements the io.Writer
interface.
*Encoder
: Object of the type Encoder
defined in the encoding/json
package.
package mainimport ("encoding/json""os""log")func main() {type Student struct {Name, Major stringRollNumber int32}stu := new(Student)stu.Name = "Hassan"stu.Major = "Physics"stu.RollNumber = 18100026enc := json.NewEncoder(os.Stdout)err := enc.Encode(&stu)log.Println(err)}
In the above example, we define a struct Student
with properties Name
, Major
, and RollNumber
and created an object stu
of type Student
. We pass standard output stream os.Stdout
to the func NewEncoder(w io.Writer) *Encoder
method which returns an Encoder
object stored in enc
. We use the Encode()
method accessible to enc
which serializes the stu
object into JSON and writes the JSON objects to the standard output stream. The Encode
method returns an error
instance which reports whether any error took place in the encoding process.