Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch multiple pages of json with jq

When calling an API, I am returned a json that can be pretty printed with

curl "https://mywebsite.com/api/cars.json&page=1" |  jq '.' 

Below is a sample output. Seeing as there are two pages of records (112 total entries and only 100 entries showing per page), what command can I use in jq to immediately fetch both pages of data?

{
  "current_page": 1,
  "per_page": 100,
  "total_entries": 112,
  "items": [
    {
      "id": 1,
      "name": "vehicleA",
      "state": "available",
      "charge": 100
    },
    {
      "id": 2,
      "name": "vehicleB",
      "state": "available",
      "charge": 75
    },
    {
      "id": 3,
      "name": "vehicleB",
      "state": "available",
      "charge": 50
    }...
like image 720
iskandarblue Avatar asked Oct 28 '25 06:10

iskandarblue


1 Answers

jq doesn't fetch pages. You need to fetch pages with multiple curl calls, and then combine the JSON outputs. For example you could get a JSON array of the combined .item properties:

url=https://mywebsite.com/api/cars.json
jq -s '.[0].items + .[1].items' <(curl "$url&page=1" | jq .) <(curl "$url&page=2" | jq .)

If you don't know in advance the number of pages you'll need, then you'll need to work a bit harder, but it's of course possible.

Get the total entries from the first page:

total=$(curl "$url&page=1" | jq .total_entries)

Compute the number of pages:

((pages = total / 100))

if ((total % 100 > 0)); then
    ((pages++))
else

And then you can write a loop to download the results page by page, generate the jq command .[0].items + ... + .[n].items and call jq with it to get the combined JSON array.

like image 60
janos Avatar answered Oct 29 '25 20:10

janos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!