LoginSignup
23
12

はじめに

先日、APIレスポンスの検証をしようと思い、curlコマンドを使用する機会がありました。
レスポンスが期待通りに返ってきていることはすぐにわかったのですが、jsonの内容をコマンドライン上で見るのはかなりきつく、どうにかならないものかと思いました。
そんな時に便利なjqコマンドがあることを学んだので、記事として残しておきます。

OpenWeatherAPIを例に

今回はOpenWeatherAPIを例にしてみます。
OpenWeatherAPIとは、ざっくり言うと天気の情報を返却してくれるAPIです。
(https://openweathermap.org/api)
実際に見た方がイメージがつきやすいと思うので、早速実践してみましょう。

curlコマンドでAPIを叩いてみる

実際にAPIを叩いてみます。
appid=xxxxの部分にはOpenWeather公式ページから取得できるAPIキーが入ります。)

curl "https://api.openweathermap.org/data/2.5/weather?q=Tokyo&units=metric&appid=xxxx"

そして返却値がこれです↓

{"coord":{"lon":139.6917,"lat":35.6895},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],"base":"stations","main":{"temp":29.87,"feels_like":30.42,"temp_min":27.59,"temp_max":32.03,"pressure":1007,"humidity":47},"visibility":10000,"wind":{"speed":7.72,"deg":200},"clouds":{"all":20},"dt":1718353818,"sys":{"type":2,"id":2044139,"country":"JP","sunrise":1718306694,"sunset":1718359093},"timezone":32400,"id":1850144,"name":"Tokyo","cod":200}

返却値、見づらいですね。

コマンドライン上だともっと見づらく、以下のようになります。
スクリーンショット 2024-06-14 17.39.52.png

特に、階層構造がどうなっているのかをここから読み解くのは、まさに職人芸...

jqを利用してみる

まずはインストール

Homebrewを利用してインストールしました。

brew install jq

早速使ってみよう

同じようにOpenWeatherAPIを叩いてみます。
| jq .の部分がポイントです。

curl "https://api.openweathermap.org/data/2.5/weather?q=Tokyo&units=metric&appid=xxxx" | jq .

返却値がこれ↓

{
  "coord": {
    "lon": 139.6917,
    "lat": 35.6895
  },
  "weather": [
    {
      "id": 801,
      "main": "Clouds",
      "description": "few clouds",
      "icon": "02d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 29.21,
    "feels_like": 30.34,
    "temp_min": 27.79,
    "temp_max": 32.03,
    "pressure": 1007,
    "humidity": 53
  },
  "visibility": 10000,
  "wind": {
    "speed": 7.72,
    "deg": 200
  },
  "clouds": {
    "all": 20
  },
  "dt": 1718354119,
  "sys": {
    "type": 1,
    "id": 8063,
    "country": "JP",
    "sunrise": 1718306694,
    "sunset": 1718359093
  },
  "timezone": 32400,
  "id": 1850144,
  "name": "Tokyo",
  "cod": 200
}

随分見やすくなりましたね。嬉しいです。

他にもいろんな機能が

要素の一部を抜き出すこともできます。例えばこんなふうに書いてやると、

curl 'https://api.openweathermap.org/data/2.5/weather?q=Tokyo&units=metric&appid=xxxx'| jq '.["main"]'

以下のように"main"をキーに持つ箇所を抜き出すことができます。

{
  "temp": 29.08,
  "feels_like": 30.15,
  "temp_min": 27.79,
  "temp_max": 32.03,
  "pressure": 1007,
  "humidity": 53
}

まとめ

コマンドライン操作は手軽な反面、どうしても出力が見づらくなってしまいがちです。
そんな時にjqを利用して返却値を見やすくできるのは嬉しいと思いました。

参考

https://openweathermap.org/api
https://jqlang.github.io/jq/manual/

23
12
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
23
12