LoginSignup
30
27

More than 5 years have passed since last update.

jqコマンドが便利な件

Last updated at Posted at 2014-02-04

テストなどでちょっとAPI叩きたい時、コマンドラインJSONパーサのjqがなかなか便利。

インストール

brew install jq

Mac以外の人はこちらから

とりあえず試す

サンプルに東電電力供給APIを借りました。ありがとうございます。

curl -s "http://tepco-usage-api.appspot.com/2014/2/3.json"|jq '.'

出力

[
  {
    "usage": 2849,
    "entryfor": "2014-02-02 15:00:00",
    "usage_updated": "2014-02-02 16:05:05",
    "forecast": 0,
    "forecast_peak_updated": "2012-02-02 23:30:00",
    "hour": 0,
    "capacity": 4756,
    "capacity_updated": "2012-02-02 23:30:00",
    "forecast_peak_usage": 3920,
    "month": 2,
    "forecast_peak_period": 18,
    "capacity_peak_period": 18,
    "year": 2014,
    "saving": false,
    "day": 3
  },
  # 以下略
]

配列の取り出し

curl -s "http://tepco-usage-api.appspot.com/2014/2/3.json"|jq '.[]'

出力

{
  "usage": 2849,
  "entryfor": "2014-02-02 15:00:00",
  "usage_updated": "2014-02-02 16:05:05",
  "forecast": 0,
  "forecast_peak_updated": "2012-02-02 23:30:00",
  "hour": 0,
  "capacity": 4756,
  "capacity_updated": "2012-02-02 23:30:00",
  "forecast_peak_usage": 3920,
  "month": 2,
  "forecast_peak_period": 18,
  "capacity_peak_period": 18,
  "year": 2014,
  "saving": false,
  "day": 3
}
{
# 以下略

値の取り出し

 curl -s "http://tepco-usage-api.appspot.com/2014/2/3.json"|jq '.[].usage'|ruby -e 'p readlines.map(&:chomp).map(&:to_i).max'                                          

出力

2917
2808
# 以下略

加工

メロスにはawkがわからぬ

 curl -s "http://tepco-usage-api.appspot.com/2014/2/3.json"|jq '.[].usage'|ruby -e 'p readlines.map(&:chomp).map(&:to_i).max'                                          

出力

3805

2/3は暖かかったんで少なめですね。

ワンライナーでちょっとAPI試す時なんかに便利ではないかと。

30
27
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
30
27