jq and array of two things: key and value
I have this script:
curl -sX 'GET' \ ' \ -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.327How can I make these two separate arrays as one?
1 Answer
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...