How to join two fields in JSON array with jq

I’m trying to get output in one line for 2 fields in the array using ‘jq’

curl -X 'GET' "https://api.coingecko.com/api/v3/coins/ethereum/market_chart?vs_currency=USD&days=10&interval=daily" -H 'accept: application/json'|jq '.prices[][]

gives me output like this:

1652227200000
2344.797715643986
1652313600000
2080.910243657776
1652400000000
1966.6991711336661
1652486400000
2010.214051125259
1652572800000
2064.229357512243
1652659200000
2147.047447880575
1652745600000
2025.8886983912162
1652832000000
2095.178884796724
1652918400000
1915.1771232664505
1653004800000
2023.8482593608173
1653070323000
1931.3963167096579

and I would like output to have date price (in one line) with space or tab in between like

1653004800000    2023.8482593608173
1653070323000    1931.3963167096579

I’ve tried with '.price[][]|join(" ")' but it didn’t work.
possibly also format price to have 2 decimal places. I was able to do it if I output only price like:

...|jq .price[][1]| xargs printf "%'.2f\n"

not sure how to do it if I have 2 values.

>Solution :

The second [] will bring you down to the elements you want to align. Omit it (but keep the first, as you want to access the elements of the .prices array), and format that array. You can, for instance, have the items tab-separated by using @tsv. Alternatively, you can use the join function with a separator string.

curl … | jq -r '.prices[] | @tsv'
1652227200000   2344.797715643986
1652313600000   2080.910243657776
1652400000000   1966.6991711336661
1652486400000   2010.214051125259
1652572800000   2064.229357512243
1652659200000   2147.047447880575
1652745600000   2025.8886983912162
1652832000000   2095.178884796724
1652918400000   1915.1771232664505
1653004800000   2023.8482593608173
1653073654000   1942.3670724677067

Demo

curl … | jq -r '.prices[] | join(" | ")'
1652227200000 | 2344.797715643986
1652313600000 | 2080.910243657776
1652400000000 | 1966.6991711336661
1652486400000 | 2010.214051125259
1652572800000 | 2064.229357512243
1652659200000 | 2147.047447880575
1652745600000 | 2025.8886983912162
1652832000000 | 2095.178884796724
1652918400000 | 1915.1771232664505
1653004800000 | 2023.8482593608173
1653073654000 | 1942.3670724677067

Demo


To format the milliseconds column, convert it to seconds (divide by 1000), then use strftime (or strflocaltime for local time) with a format string. To round the price column to two decimals, multiply it by 100, use round and divide again.

curl … | jq -r '.prices[]
  | .[0] |= (./1000 | strftime("%d-%m-%Y"))
  | .[1] |= (. * 100 | round / 100)
  | @tsv
'
11-05-2022  2344.8
12-05-2022  2080.91
13-05-2022  1966.7
14-05-2022  2010.21
15-05-2022  2064.23
16-05-2022  2147.05
17-05-2022  2025.89
18-05-2022  2095.18
19-05-2022  1915.18
20-05-2022  2023.85
20-05-2022  1942.37

Demo

Leave a Reply