Skip to content

Instantly share code, notes, and snippets.

@fujiwara
Created December 25, 2015 07:42
Show Gist options
  • Save fujiwara/1f80116d24d39c17f31c to your computer and use it in GitHub Desktop.
Save fujiwara/1f80116d24d39c17f31c to your computer and use it in GitHub Desktop.
Read from stdin as JSON or not JSON
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))
}
}
$ 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