DEV Community

Aniket Satbhai
Aniket Satbhai

Posted on

Using jq to filter JSON data

Basic Elements

  • .
    . - Same as input when used standalone,
    .key - Value of the key

  • []
    [] - Select array,
    [n] - Select nth element in the array,
    [.key1, .key2, ..] - Create new json object

  • {}
    {key1: .key1, key2: .key2, ..}
    or
    {key1, key2, ..} - Create new json object

n ∉ [0, ∞), int

Ex.

file.json

[
  {
    "id": 1,
    "name": "test1"
  },
  {
    "id": 2,
    "name": "test2"
  }
]
Enter fullscreen mode Exit fullscreen mode

To filter ids:

$ jq '.[].id' file.json
1
2
$ cat file.json | jq '.[] | .id'
1
2
$ cat file.json | jq '.[].id'
1
2
Enter fullscreen mode Exit fullscreen mode

To return value of name key when id is 1

$ jq '.[] | select(.id == 1) | .name' file.json
"test1"
$ cat file.json | jq '.[] | select(.id == 1) | .name'
"test1"
Enter fullscreen mode Exit fullscreen mode

To filter ids as json

$ jq '.[] | {id}' file.json
{
  "id": 1
}
{
  "id": 2
}
$ cat file.json | jq '.[] | {id}'
{
  "id": 1
}
{
  "id": 2
}
$ cat file.json | jq '.[] | {id: .id}'
{
  "id": 1
}
{
  "id": 2
}
Enter fullscreen mode Exit fullscreen mode

Ref. :
https://stedolan.github.io/jq/
https://programminghistorian.org/en/lessons/json-and-jq

Top comments (0)