Passing variable to jq to edit a json file

10,288

You can use square bracket indexing on all objects in jq, so [$name] works for what you're trying:

jq --arg key1 true --arg name "$name" '.Linux.script_executed[$name] = $key1 ...' 

This use of square brackets is not very well documented in the manual, which makes it look like you can only use .[xyz], but ["x"] works anywhere that .x would have as long as it's not right at the start of an expression (that is, .a.x and .a["x"] are the same, but ["x"] is an array construction).

Note the use of single quotes above - that is so Bash won't try to interpret $name and $key1 as shell variables. You should keep the double quotes for --arg name "$name", because that really is a shell variable, and it should be quoted to make it safe to use.

Share:
10,288

Related videos on Youtube

Rakib Fiha
Author by

Rakib Fiha

Aerospace Eng

Updated on September 18, 2022

Comments

  • Rakib Fiha
    Rakib Fiha over 1 year

    I am trying to pass a variable into jq like this '.Linux.date.$var' so far I have tried quoting them by name which is working fine. But I want to use variable to call them.

    I have this, which is working fine

    exectime=$(date -d now);    
    cp $check_exec_history $check_exec_history.tmp
        jq --arg key1 true --arg key2 "$exectime" --arg name "$name" '.Linux.script_executed.first = $key1 | .Linux.date_executed.first = $key2' $check_exec_history.tmp > $check_exec_history; 
        rm $check_exec_history.tmp;
    

    I want to get to this, but not working:

    name=first;
    exectime=$(date -d now);
    cp $check_exec_history $check_exec_history.tmp
    jq --arg key1 true --arg key2 "$exectime" --arg name "$name" ".Linux.script_executed.$name = $key1 | .Linux.date_executed.$name = $key2" $check_exec_history.tmp > $check_exec_history; 
    rm $check_exec_history.tmp;
    

    I came this far: using this answer https://stackoverflow.com/q/40027395/9496100 But I am not sure where I am doing mistake.

    name=first;
    exectime=$(date -d now);    
    cp $check_exec_history $check_exec_history.tmp
        jq --arg key1 true --arg key2 "$exectime" --arg name "$name" '.Linux.script_executed.name==$name = $key1 | .Linux.date_executed.name==$name = $key2' $check_exec_history.tmp > $check_exec_history; rm $check_exec_history.tmp;
    
  • eephillip
    eephillip about 3 years
    Had to use -n/--null-input two work without piped input name=foobar; jq -n --arg key1 true --arg name "$name" '.Linux.script_executed[$name] = $key1'
  • Ashish Sharma
    Ashish Sharma over 2 years
    Square bracket help me and fix my issue. Below is sample I used in my case: RUNNER_TOKEN=$(aws secretsmanager get-secret-value --secret-id $SECRET_ID | jq '.SecretString|fromjson' | jq --arg kt $SECRET_KEY -r '.[$kt]' | tr -d '"')