Golang encoding/json.Marshal() function example

package encoding/json

Marshal returns the JSON encoding of v. ( see http://golang.org/pkg/encoding/json/#Marshal for full description )

Golang encoding/json.Marshal() 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:  36,
 Job:  "CEO",
 }

 output, err := json.Marshal(worker) // <--- here

 if err != nil {
 fmt.Println(err)
 os.Exit(1)
 }

 fmt.Println(string(output))

 // os.Stdout.Write(b) -- also ok

 }

Output :

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

Reference :

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

Advertisement