26
32

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.

シェルスクリプトでJSONを扱う

Posted at

入出力がJSON形式のWeb APIを呼び出すシェルスクリプトを実装する必要があったため、簡単にJSONを扱う方法を調査した。

結論としては、Web APIへ入力するJSONの作成にはヒアドキュメントを使い、Web APIから出力されたJSONの解析にはjqを使うこととした。

サンプルコード

number=1
string="abc"

# JSON作成にはヒアドキュメントを使う
json=$(cat << EOS
{
  "number": ${number},
  "string": "${string}"
}
EOS
)

echo "$json"
# => {
#      "number": 1,
#      "string": "abc"
#    }

# JSON解析にはjqを使う 
echo $JSON | jq '.number'
# => 1  

# -r: string型の"を除去する
echo $JSON | jq -r '.string'
# => abc

参考

26
32
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
26
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?