LoginSignup
22
21

More than 5 years have passed since last update.

node.jsのjsonコマンドを使って、bash(shell)からでも簡単JSONパース

Last updated at Posted at 2013-01-10

この記事は最終更新から1年以上経過しています。 気をつけてね。

Infrastructure as codeの実践では意外とJSONの敷居が高いが、インフラ屋がもっとJSONと仲良くなるためのツールがある。
Shellから使いやすければ、他のツールとも連携がしやすくなる…はず。

ちなみにJoyentのSmartOS(SmartMachine)では仮想サーバ作成直後からjsonコマンドが使えてラク。

jsontoolのインストール

node.jsは好きなようにに導入して、npm。

ShellOut
$ npm install -g jsontool
$ json --version
json 5.1.1

ソースのリポジトリはこちらhttps://github.com/trentm/json

サンプルJsonファイルを作る

metadata.json
{
    "metadata": {
        "user-script": "",
        "credentials": {
            "root": "root_password",
            "admin": "admin_password",
            "mysql": "mysql_password",
            "pgsql": "pgsql_password"
        }
    }
}

パースして出力する

jsonコマンドのオプションにキーを指定するとValueが取得できる、階層をつけるなら.(ピリオド)で区切る。

ShellOut
$ cat metadata.json | json metadata.credentials      
{
  "root": "root_password",
  "admin": "admin_password",
  "mysql": "mysql_password",
  "pgsql": "pgsql_password"
}

$ cat metadata.json | json metadata.credentials.mysql
mysql_password

テキスト処理を使って自力でパースするのとは雲泥の差!

スクリプトファイル内で扱う

sample.sh
MYSQL_PASS=`cat metadata.json | json metadata.credentials.mysql`  
echo ${MYSQL_PASS}
mysql_password

catでやっているが、王道はcurlで他所のAPIからの取得でしょう。

22
21
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
22
21