Help us understand the problem. What is going on with this article?

shellでjsonを扱う方法

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

一回だけ値を使う場合

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

asukiaaa
おいしい食事と心地良い睡眠を楽しむために生きています。
https://asukiaaa.blogspot.com
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした