Created
June 6, 2017 12:23
-
-
Save inancgumus/160d3d1e4db2802ef8eee5fedd3e691e to your computer and use it in GitHub Desktop.
Serialize (Marshall) JSON into a writable stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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