LoginSignup
44
42

More than 5 years have passed since last update.

Vim (with python) で json を整形

Last updated at Posted at 2013-02-07

整形されていない json を持ってきて vim で見やすく整形したい。

  1. 例えばどこかのAPIを叩いて取得した値
  2. 例えばどこかのドキュメントに載っている値
  3. 例えばサンプルをドキュメントに残すために手作業で作った値

などなど。1番目の例であればブラウザの拡張を使うことで、綺麗に表示できたりもしますが、2番目3番目の場合に vim にぺたっと貼り付けて整形できると、便利そうです。

python2.6以降がインストールされている環境で(python コマンドに PATH が通っている状態で)、下記コマンドを叩くとバッファ内の json 文字列を整形することができます。

:%!python -m json.tool

例えば、こんな文字列がバッファに入っている時に上記コマンドを叩くと

{"count":1,"list":[{"url":"http://json.org/example.html","title":"\u3042\u3044\u3046\u3048\u304a"}]}

こんな感じになります。

{
    "count": 1, 
    "list": [
        {
            "title": "\u3042\u3044\u3046\u3048\u304a", 
            "url": "http://json.org/example.html"
        }
    ]
}

良い感じです。しかし、日本語がエスケープされたままではあまり嬉しくありません(また行末尾に半角スペースが入っていたりするのも気になります)。というわけで、少し改良したコマンドを作ってみました。vim 初心者なので、ツッコミもらえると嬉しいです。

command! JsonFormat :execute '%!python -m json.tool'
  \ | :execute '%!python -c "import re,sys;chr=__builtins__.__dict__.get(\"unichr\", chr);sys.stdout.write(re.sub(r\"\\u[0-9a-f]{4}\", lambda x: chr(int(\"0x\" + x.group(0)[2:], 16)), sys.stdin.read()))"'
  \ | :%s/ \+$//ge
  \ | :set ft=javascript
  \ | :1

簡単に説明を書くと

  1. python の json.tool で整形
  2. "\u307d" のような unicode 文字列をデコード
  3. 各行の末尾にスペースが入るので削除
  4. vim の filetype を javascript にしてハイライト表示
  5. カーソルを先頭行に移動

コマンドを実行すると

:JsonFormat

下記のような表示になります。

{
    "count": 1,
    "list": [
        {
            "title": "あいうえお",
            "url": "http://json.org/example.html"
        }
    ]
}
44
42
1

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
44
42