標準入力から「JSON、もしくはそれ以外のなにか」が流れてきた場合に、先頭1バイトを見て {
で始まっていたらJSONとして、そうでなければ行単位で読み込みたい、というのをGoで書く。
bufio.ReaderのPeek を使うとできます。
(thanks to @acidlemon)
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]