Home > Net >  How to specify jq output fields from variable in bash?
How to specify jq output fields from variable in bash?

Time:01-16

given the following (simplified) json file:

{
    "data": [
        {
            "datum": "2023-01-11 00:00:00",
            "prijs": "0.005000",
            "prijsZP": "0.161550",
            "prijsEE": "0.181484",
            "prijsTI": "0.160970",
        },
        {
            "datum": "2023-01-11 01:00:00",
            "prijs": "0.000000",
            "prijsZP": "0.155500",
            "prijsEE": "0.175434",
            "prijsTI": "0.154920",
        }
  ]
}

I want to specify in my jq command which fields to retreive, i.e. only "datum" and "prijsTI". But on another moment this selection will be different.

I use the following command to gather all the fields, but would like to set the field selection via a variable:

cat data.json |jq -r '.data[]|[.datum, .prijsTI]|@csv'

I already tried using arguments, but this did not work :-(

myJQselect=".datum, .prijsTI"
cat data.json |jq -r --arg myJQselect "$myJQselect" '.data[$myHour |tonumber]|[$myJQselect]|@csv'

gives the following result: ".datum, .prijs" instead of the correct values.

Would this be possible?

Thanks,

Jeroen

CodePudding user response:

You can use the --args option to provide a variable number of fields to query, then use the $ARGS.positional array to retrieve them:

jq -r '.data[] | [.[$ARGS.positional[]]] | @csv' data.json --args datum prijsTI
"2023-01-11 00:00:00","0.160970"
"2023-01-11 01:00:00","0.154920"
  • Related