Home > front end >  Can't use variable as path - is not defined at <top-level>,
Can't use variable as path - is not defined at <top-level>,

Time:03-03

Here bash script using jq to parse json

ruleTypes=( 
       ["Bugs"]=0 
       ["Vulnerabilities"]=0 
       ["CodeSmells"]=0
       ["SecurityHotspots"]=0        
     )

for rulesTypeKey in "${!ruleTypes[@]}"; do
  #echo "rules types $rulesTypeKey = ${ruleTypes[$rulesTypeKey]}"
  for currentActivation in ${ACTIVATION_ARRAY[@]}; do
      rulesResponse=$(curl -s -XGET "$RULES_REQUEST_URL_PREFIX&activation=$currentActivation&types=$rulesTypeKey&p=1&ps=1")
      totalRules=$(jq -r '.total' <<< "$rulesResponse")
      ruleTypes[$rulesTypeKey]=$totalRules
      jq --argjson totalArg "$totalRules" '.rules.active.Bugs = $totalArg ' <<<$RULES_REPORT_INIT_JSON >$FILE_REPORT_RULES      
  done
done

This work fine. Nice.

Now I want to use variable $path for path. I try this:

ruleTypes=( 
       ["Bugs"]=0 
       ["Vulnerabilities"]=0 
       ["CodeSmells"]=0
       ["SecurityHotspots"]=0        
     )

for rulesTypeKey in "${!ruleTypes[@]}"; do
  #echo "rules types $rulesTypeKey = ${ruleTypes[$rulesTypeKey]}"
  for currentActivation in ${ACTIVATION_ARRAY[@]}; do
      rulesResponse=$(curl -s -XGET "$RULES_REQUEST_URL_PREFIX&activation=$currentActivation&types=$rulesTypeKey&p=1&ps=1")
      totalRules=$(jq -r '.total' <<< "$rulesResponse")
      ruleTypes[$rulesTypeKey]=$totalRules
      path=".rules.active.$rulesTypeKey"
      jq --argjson totalArg "$totalRules" '$path = $totalArg ' <<<$RULES_REPORT_INIT_JSON >$FILE_REPORT_RULES      
  done
done

But I get error:

jq: error: $path is not defined at <top-level>, line 1:
$path = $totalArg 
jq: 1 compile error

P.S

I try this (double quotes):

jq --argjson totalArg "$totalRules" "$path = $totalArg" <<<$RULES_REPORT_INIT_JSON >$FILE_REPORT_RULES . 

But get error:

jq: error: syntax error, unexpected $end (Unix shell quoting issues?) at <top-level>, line 1: 

CodePudding user response:

If $totalRules is supposed to be a number you should drop the -r option when reading it

totalRules=$(jq '.total' <<< "$rulesResponse")

and use --argjson when setting it

jq --arg key "$rulesTypeKey" --argjson total "$totalRules" \
  '.rules.active[$key] = $total'

If $totalRules may also produce raw text (in edge cases, for instance), and you want to store that value as string, leave the -r option when reading it, and use --arg when setting it:

jq --arg key "$rulesTypeKey" --arg total "$totalRules" \
  '.rules.active[$key] = $total'

CodePudding user response:

You have single quotes around your argument:

'$path = $totalArg ' 

Therefore variables won't be expanded by the shell, and jq sees the literal string $path, which is undefined. If you had used double quotes, both path and totalArg would be expanded.

  • Related