DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.