Search code examples
jsonvariablesjq

Using jq with the value of a variable as field value


I have a JSON file which I got via curl with hourly energy prices.

I can output the price for 6 o'clock with

jq '.energy | .todayHours | .[6] | .priceIncludingVat' < "$JSON"

I get the actual hour via date command: HOUR=$(date '+%-H')

How do I get the price for the actual hour? I have no clue how to insert the value of $HOUR into the jq query instead of the "6"

Thanks a lot!

Played around with different things I found e.g. with the "--arg" option but got nowhere, but maybe I tried them a wrong way :-(


Solution

  • As HOUR is a number, you can use --argjson instead of --arg. The (only) benefit is that you won't have to do the conversion from string to number yourself:

    jq --argjson hour "$HOUR" '.energy.todayHours[$hour].priceIncludingVat' < "$JSON"