5
1

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 3 years have passed since last update.

jqでselectした結果をJSONの配列として出力する

Posted at

普通に jq select すると結果が列挙されるだけなのをなんとかする。

example

例えばこんなJSONがあったときに

cinema.json
[
  {
    "key": "David",
    "value": "seven"
  },
  {
    "key": "Robert",
    "value": "dusk"
  },
  {
    "key": "David",
    "value": "game"
  }
]

jq select でデータを抜き出すと、こんな感じになる。

> cat cinema.json | jq '.[] | select(.key=="David")'
{
  "key": "David",
  "value": "seven"
}
{
  "key": "David",
  "value": "game"
}

これをちゃんとJSONの配列形式にしてやりたい。

配列出力する

そんなときは jq -s '.'を追加すればよい。

> cat cinema.json | jq '.[] | select(.key=="David")' | jq -s '.'
[
  {
    "key": "David",
    "value": "seven"
  },
  {
    "key": "David",
    "value": "game"
  }
]

-sオプションの意味は以下の通り。

-s		read (slurp) all inputs into an array; apply filter to it;

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?