LoginSignup
11
10

More than 5 years have passed since last update.

Goで標準入力の先頭をみてJSONとして読むかどうか切り替える

Posted at

標準入力から「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]
11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10