LoginSignup
1
0

jqコマンドが使えず無理やりシェルコマンドでJSONの値を取得する方法

Last updated at Posted at 2023-09-30

jqコマンドがインストールされておらず、しょうがなくjqコマンドの代わりにgrepsedtrcutコマンドを使用して取得した時の方法を紹介します。

1. jsonファイル

以下のjsonファイルを対象とします。

test.json
{"key01":"value01","key02":"value02","key03":"value03","key04":"value04","key05":"value05"}

2. jqコマンドでの取得方法

jqコマンドだと以下のコマンドで取得できます。

cat test.json | jq -r .key02

実行結果
[root@centos85 ~]# cat test.json | jq -r .key02
value02
[root@centos85 ~]#

3. 通常のコマンドで無理やり取得する方法

jqコマンドが使えなかったので、以下のコマンドで取得しました。

cat test.json | sed 's/^{\(.*\)}$/\1/' | tr ',' '\n' | grep key02 | cut -d ":" -f 2 | tr -d '\t' | tr -d ' ' | tr -d '"'

  • sed 's/^{\(.*\)}$/\1/'のコマンドで{}内の文字列を取得
  • tr ',' '\n'のコマンドで,\n(改行)に置換
  • grepコマンドでkey02の行を抽出
  • cutコマンドで:で分割し2項目目を取得
  • tr -dコマンドで\t(タブ)、半角スペースを削除
  • tr -dコマンドで"を削除
実行結果
[root@centos85 ~]# cat test.json | sed 's/^{\(.*\)}$/\1/' | tr ',' '\n' | grep key02 | cut -d ":" -f 2 | tr -d '\t' | tr -d ' ' | tr -d '"'
value02
[root@centos85 ~]#

今回のjsonファイルは入れ子がなかったので単純にできましたが、入れ子がある場合はもっと考えないといけません。


以上

1
0
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
1
0