Skip to content

Instantly share code, notes, and snippets.

@Owanesh
Created November 3, 2021 09:33
Show Gist options
  • Save Owanesh/2527491bc366c6b7d9833dcc91c529c6 to your computer and use it in GitHub Desktop.
Save Owanesh/2527491bc366c6b7d9833dcc91c529c6 to your computer and use it in GitHub Desktop.
Example of (basic) jq query
[{
"store": {
"books": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Omoo",
"isbn": "978-1169307773",
"price": 40.14
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Brideshead Revisited",
"price": 14.99
}
]
}
}]
@Owanesh
Copy link
Author

Owanesh commented Nov 3, 2021

(basic) Querying with jq

With an input as file bookstore.json, we can easily do some basic query

How many books there are, over 8$ and under 12$ ?

jq '[.[].store.books[] | select(.price >= 8 and .price < 12)] | length' your_file.json

>>> 2

How many books have been written by each author?

jq '.[].store.books | group_by(.author)[]  | {author: .[0].author, length: length} ' your_file.json

and output will be

  {
    "author": "Evelyn Waugh",
    "length": 2
  },
  {
    "author": "Herman Melville",
    "length": 2
  },
  {
    "author": "J. R. R. Tolkien",
    "length": 1
  },
  {
    "author": "Nigel Rees",
    "length": 1
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment