LoginSignup
5
5

More than 5 years have passed since last update.

json を pretty print するのに echo '{"apple": "red", "lemon": "yellow"}' | python -m json.tool は冗長じゃないですか?なので go でコマンド用意しました

Last updated at Posted at 2014-10-11

概要

json をインデントしてきれいに表示する方法をググったら

echo '{"apple": "red", "lemon": "yellow"}' | python -m json.tool 

というのを見つけました.普段から python つかってるならあれだけど,引数書くのめんどいしちょっと大げさじゃないですかね.1コマンドで済ませたいところ.ちっちゃいコマンド作るのは go の得意分野なので用意してみました.って,書いてみてから別のツールがありそうな気がしてきたけど,go はクロスコンパイルできるので win, mac, linux といろいろ使えるからいいことにしました.

コード

これだけ.

pretty.go
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "os"
)

func main() {
    var j bytes.Buffer
    io.Copy(&j, os.Stdin)
    var dst bytes.Buffer
    if e := json.Indent(&dst, j.Bytes(), "", "    "); e != nil {
        fmt.Fprintln(os.Stderr, "pretty: %v", e)
    }
    fmt.Println(dst.String())
}

インストール

go get github.com/ikawaha/pretty

使い方

標準入力から受けて標準出力に吐くだけ.

 $ echo '{"apple": "red", "lemon": "yellow"}' | pretty
{
    "apple": "red",
    "lemon": "yellow"
}
5
5
2

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
5
5