インストール
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"
}
]