5
4

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 1 year has passed since last update.

json整形コマンドラインツール"jq"

Last updated at Posted at 2017-11-21

インストール

brew install jq

jqは引数に様々なフィルタをパイプ(|)でつなげた形式で処理を指定します。

jq [オプション] 'フィルタ1 | フィルタ2 | フィルタ3 | ...' [入力ファイル]

とりあえず試す。apiからのjsonファイルを整形
'.'は入力データそのものを表す。

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
}
{
# 以下略

ローカルjsonファイルを整形

(meibo.json)

{"name":"john","gender":"m","age":"18"}
{"name":"paul","gender":"m","age":"20"}
{"name":"alice","gender":"f","age":"15"}
{"name":"dabid","gender":"m","age":"17"}
{"name":"jasmin","gender":"f","age":"17"}

jsの引数にファイルを指定

$ jq "." meibo.json
[
  {
    "name": "john",
    "gender": "m",
    "age": "18"
  },
  {
    "name": "paul",
    "gender": "m",
    "age": "20"
  },
  {
    "name": "alice",
    "gender": "f",
    "age": "15"
  },
  {
    "name": "dabid",
    "gender": "m",
    "age": "17"
  },
  {
    "name": "jasmin",
    "gender": "f",
    "age": "17"
  }
]

catでjsonファイルを標準出力して、それをパイプでjqコマンド受け取る

(cat コマンド)
ファイルまたは標準入力の内容をそのまま標準出力に出力する。

$ cat meibo.json | jq .
[
  {
    "name": "john",
    "gender": "m",
    "age": "18"
  },
  {
    "name": "paul",
    "gender": "m",
    "age": "20"
  },
  {
    "name": "alice",
    "gender": "f",
    "age": "15"
  },
  {
    "name": "dabid",
    "gender": "m",
    "age": "17"
  },
  {
    "name": "jasmin",
    "gender": "f",
    "age": "17"
  }
]
5
4
1

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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?