1

I have this script:

curl -sX 'GET' \
  'https://api.coingecko.com/api/v3/exchange_rates' \
  -H 'accept: application/json' | jq -rc '.[]|select(.)|keys,(.[].value|tostring)'

and the source of the JSON is:

{
  "rates": {
    "btc": {
      "name": "Bitcoin",
      "unit": "BTC",
      "value": 1,
      "type": "crypto"
    },
    "eth": {
      "name": "Ether",
      "unit": "ETH",
      "value": 14.327,
      "type": "crypto"
    }, ...

I cannot make pairs key (coin id, "btc")-value (value of the coin, "1"), what I need is the id of the coin and its value:

btc 1
eth 14.327

How can I make these two separate arrays as one?

1 Answer 1

3

You can get pairs by using the to_entries filter. It will transform the dict into an array of items:

$ curl <url> | jq ".rates | to_entries"

[
    {
        "key": "btc",
        "value": {
            "name": "Bitcoin",
            "unit": "BTC",
            "value": 1,
            "type": "crypto"
        }
    },
    {
        "key": "eth",
        "value: {...}
    },
    },
    { ... }
]

Once you have such entries, you can access .key and .value.value of each item to get the pairs you want:

$ curl <url> | jq '.rates | to_entries | .[] | [.key, .value.value]'

["btc", 1]
["eth", 14.376]
[...]

The same for transforming them into a string:

$ curl <url> | jq -r '.rates | to_entries | .[] | "\(.key) \(.value.value)"'
btc 1
eth 14.368
...

Note that the select(.) you had before seems completely redundant...

1
  • Thank you! Amazing!
    – pbies
    Oct 31, 2021 at 16:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .