Skip to content

Instantly share code, notes, and snippets.

@inancgumus
Created June 6, 2017 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inancgumus/160d3d1e4db2802ef8eee5fedd3e691e to your computer and use it in GitHub Desktop.
Save inancgumus/160d3d1e4db2802ef8eee5fedd3e691e to your computer and use it in GitHub Desktop.
Serialize (Marshall) JSON into a writable stream
package main
import (
"bufio"
"encoding/json"
"fmt"
"os"
)
func main() {
// create a json, then serialize into json
json, _ := json.Marshal(struct {
Name string
Age int
}{"foo", 42})
// directly print to stdout:
fmt.Println(string(json))
// write into a stream:
// **** here in standard out ****
output := os.Stdout
// **** however, this could also be a file: ****
// output, _ := os.OpenFile("foo.txt", os.O_CREATE|os.O_WRONLY, 0644)
// defer output.Close()
w := bufio.NewWriter(output)
w.WriteString(string(json))
w.Flush()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment