LoginSignup
8
8

More than 5 years have passed since last update.

jqのバージョンを最新にしたらjsonの処理が捗りすぎて怖い

Last updated at Posted at 2014-02-08

jsonの処理はjqに任せるとすこぶる捗るというのは有名ですが、Homebrewとかで入れた場合は、そのすごさが発揮されていないことがわかりました。

バージョン見ると1.3で最新版っぽいんですが、どうも英語マニュアルに載ってる機能のいくつかが使えなくて困っていました。

jqのマニュアル (日本語)

英語には、splitとか便利っぽいのが載っているのですが、日本語には載っていないので、最近更新された新しい機能のようです。

jqの最新版をgitから落としてきてコンパイルして新しいjqを体験しましょう。

新しいjqのコンパイルでちょっとはまる

前提として、mac(mavericks)で作業してます。

作業の流れとしては、

$ git clone https://github.com/stedolan/jq.git
$ cd jq
$ autoreconf -i
$ ./configure
$ make

となるのですが、少し詰まりました。

autoreconf

automakeを入れてないと、aclocalがないって怒られます。

$ brew install automake

configure

configureのところで、bisonが古いって怒られます。

$ brew install bison

で新しいbisonがインストールできるのですが、/usr/local/binにシンボリックリンクが張られないので、エラーになっていました。
手動でリンク張りましょう。

$ cd /usr/local/bin
$ ln -s ../Cellar/bison/3.0.2/bin/bison bison
$ ln -s ../Cellar/bison/3.0.2/bin/yacc yacc

split機能を使ってみる

こういうjsonファイルがあるとします。

example.json
{"messages":[{"date":"2014-02-06T10:01:07+0900","from":{"name":"daxanya (-v-)","user_id":544xxx},"message":"https:\/\/github.com\/bowery\/orcheTstrate.js"},{"date":"2014-02-06T10:01:11+0900","from":{"name":"daxanya (-v-)","user_id":544xxx},"message":"orchestrate.js"},{"date":"2014-02-06T10:01:18+0900","from":{"name":"daxanya (-v-)","user_id":544xxx},"message":"http:\/\/www.slideshare.net\/who_you_me\/neo4j-24294061"},{"date":"2014-02-06T10:01:22+0900","from":{"name":"daxanya (-v-)","user_id":544xxx},"message":"\u30b0\u30e9\u30d5\u30c7\u30fc\u30bf\u30d9\u30fc\u30b9\u300cNeo4j\u300d\u306e \u5c0e\u5165\u306e\u5c0e\u5165"}]}

普通にjq使うと、

$ cat example.json | jq '.messages[] | .date+" "+.message'
"2014-02-06T10:01:07+0900 https://github.com/bowery/orcheTstrate.js"
"2014-02-06T10:01:11+0900 orchestrate.js"
"2014-02-06T10:01:18+0900 http://www.slideshare.net/who_you_me/neo4j-24294061"
"2014-02-06T10:01:22+0900 グラフデータベース「Neo4j」の 導入の導入"

こういう結果が得られるのですが、もうちょっと日時のところを加工したいなーと思ってもsedとかに頼らざるを得なくて困っていたのです。

最新版ではsplitが使えるのでこういうことができます。

$ cat example.json | jq 'def a(f): f|split("T")|.[1]|split("+")|.[0]; .messages[] | a(.date)+" "+.message' 
"10:01:07 https://github.com/bowery/orcheTstrate.js"
"10:01:11 orchestrate.js"
"10:01:18 http://www.slideshare.net/who_you_me/neo4j-24294061"
"10:01:22 グラフデータベース「Neo4j」の 導入の導入"

defと併用すると、特定の要素のみにsplitが適用できるので、他の要素に影響されることなく分割できます。便利!

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