72
62

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

shellでjsonを扱う方法

Last updated at Posted at 2016-01-25

やり方が分かるまでに時間がかかったので、備忘録を兼ねて共有します。

一回だけ値を使う場合

curlとjqをパイプラインで繋げます。

deal_json_once.sh
curl $URL_TO_GET_JSON | jq "."

jsonを使いまわしたい場合

curl, echo, jqを使って、jsonのechoをパイプランでjqに渡します。

deal_json_multiple.sh
JSON_RESPONSE=$(curl $URL_TO_GET_JSON)
echo $JSON_RESPONSE | jq "."
echo $JSON_RESPONSE | jq ".id"
echo $JSON_RESPONSE | jq ".name"

値を変数に入れたい場合

変数に入れたい値のechoを$()で括ります。
文字列の"が要らないなら、-rオプションを渡して消します。

JSON_RESPONSE=$(curl $URL_TO_GET_JSON)
GOT_ID=$(echo $JSON_RESPONSE | jq ".id")
GOT_NAME=$(echo $JSON_RESPONSE | jq ".name" -r)

誰かの役に立てば嬉しいです。

参考

http://stackoverflow.com/questions/20488315/read-the-json-data-in-shell-script
https://stedolan.github.io/jq/manual/
https://github.com/stedolan/jq/issues/250

72
62
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
72
62

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?