LoginSignup
8
8

More than 5 years have passed since last update.

jqを使って今日の天気を取得

Posted at

最近、jqコマンドを覚えました。めっちゃ便利ですね、これ。

"jq"でググってたら、こちらの記事(shell - シェルで今日の天気予報表示 - Qiita)に辿り着いたので、練習にとこれを改造してみました。
かなり適当なので汚いですが…

シェルでやってみる

WEATHER_CITY=130010
curl -s http://weather.livedoor.com/forecast/webservice/json/v1\?city\=$WEATHER_CITY | jq -r '.location.prefecture+" - "+.location.city+" ( "+.publicTime+" 発表 )\n  今日の天気は "+.forecasts[0].telop+"\n  最高気温: "+ if .forecasts[0].temperature.max == null then "不明" else .forecasts[0].temperature.max.celsius+"℃" end +" / 最低気温: "+ if .forecasts[0].temperature.min == null then "不明" else .forecasts[0].temperature.min.celsius+"℃"end'

こちらを実行するとこんな感じに表示されます。

東京都 - 東京 ( 2014-02-11T17:00:00+0900 発表 )
  今日の天気は 曇り
  最高気温: 不明 / 最低気温: 不明

WEATHER_CITY=130010 で表示したい地点のIDを指定してください。(ID一覧
130010で東京都の東京を表してます。

最高気温と最低気温が"不明"と表示されていますが、どうも天気予報の取得に利用しているAPI(Weather Hacks)の仕様らしく、時間帯によっては気温の部分がnullで返ってくるぽいです。
(そもそも定時に気象庁の発表している情報に気温の情報が含まれてないんですかね)

シェル関数にしてみる

weather() { curl -s http://weather.livedoor.com/forecast/webservice/json/v1\?city\=$1 | jq -r '.location.prefecture+" - "+.location.city+" ( "+.publicTime+" 発表 )\n  今日の天気は "+.forecasts[0].telop+"\n  最高気温: "+ if .forecasts[0].temperature.max == null then "不明" else .forecasts[0].temperature.max.celsius+"℃" end +" / 最低気温: "+ if .forecasts[0].temperature.min == null then "不明" else .forecasts[0].temperature.min.celsius+"℃"end' }

とすることで、以下の様なコマンドの形で利用できるようになります。

$ weather 130010
東京都 - 東京 ( 2014-02-11T17:00:00+0900 発表 )
  今日の天気は 曇り
  最高気温: 不明 / 最低気温: 不明

さらにこれを~/.zshrc~/.bashrcに記述しておくことで、いつでも今日の天気をチェックすることができます
いちいちブラウザ開いて天気予報サイト開く手間が省けますね!

以上です。

8
8
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
8
8