Created
December 25, 2015 07:42
-
-
Save fujiwara/1f80116d24d39c17f31c to your computer and use it in GitHub Desktop.
Read from stdin as JSON or not JSON
This file contains hidden or 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() { | |
reader := bufio.NewReader(os.Stdin) | |
b, _ := reader.Peek(1) | |
if string(b) == "{" { | |
var v interface{} | |
dec := json.NewDecoder(reader) | |
dec.Decode(&v) | |
fmt.Println("json", v) | |
} else { | |
line, _, _ := reader.ReadLine() | |
fmt.Println("line", string(line)) | |
} | |
} |
This file contains hidden or 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
$ echo foo | go run main.go | |
line foo | |
$ echo '{"foo":"bar"}' | go run main.go | |
json map[foo:bar] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment