Golang encoding/json.NewEncoder() function example

package encoding/json

NewEncoder returns a new encoder that writes to w ( 1st parameter )

Golang encoding/json.NewEncoder() function usage example

 package main

 import (
 "encoding/json"
 "fmt"
 "os"
 )

 type Employee struct {
 Name string
 Age  int
 Job  string
 }

 func main() {

 worker := Employee{
 Name: "Adam",
 Age:  20,
 Job:  "CEO",
 }

 encoder := json.NewEncoder(os.Stdout) //output to screen

 if err := encoder.Encode(worker); err != nil {
 fmt.Println(err)
 }

 }

Output :

{"Name":"Adam","Age":20,"Job":"CEO"}

Reference :

http://golang.org/pkg/encoding/json/#NewEncoder

Advertisement