LoginSignup
36
20

More than 5 years have passed since last update.

jqでJSONパースできない行のエラーを無視する

Posted at

JSON形式のログとかいい感じにパースして加工するのにjq便利なんだけど、たまに入力データがおかしくて、JSONパースできない行が混じってるとこんなかんじでエラーが出て途中で止まる。

例えばこんなかんじで途中にerrorとか謎の行が入ってるファイルをjqに流し込むと、

$ cat test.log
{"aaa": 111, "bbb": 112}
{"aaa": 211, "bbb": 212}
error
{"aaa": 311, "bbb": 212}

こんなかんじでエラーで止まる。

$ cat test.log | jq -r '.aaa'
111
211
parse error: Invalid numeric literal at line 4, column 0

エラーで止めたい場合もあるけど、単にJSONパースできない場合は無視してほしいときもある。

そういう場合は、どうすればよいか調べたところ、
-R(--raw-input) で入力行をパースせずに読み込んで fromjson でJSONパースしつつ ? でパースできなかったら単に無視して、 | で後ろに流してやるとよいみたい。

$ cat test.log | jq -r -R 'fromjson? | .aaa'
111
211
311

参考: https://github.com/stedolan/jq/issues/884

36
20
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
36
20