这里使用jq解析json 的bash脚本
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
这很好。美好的
现在我想使用变量$path作为路径。我试试这个:
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
但我得到错误:
jq: error: $path is not defined at <top-level>, line 1:
$path = $totalArg
jq: 1 compile error
p.S
我试试这个(双引号(:
jq --argjson totalArg "$totalRules" "$path = $totalArg" <<<$RULES_REPORT_INIT_JSON >$FILE_REPORT_RULES .
但是得到错误:
jq: error: syntax error, unexpected $end (Unix shell quoting issues?) at <top-level>, line 1:
如果$totalRules
应该是一个数字,那么在读取时应该去掉-r
选项
totalRules=$(jq '.total' <<< "$rulesResponse")
并在设置时使用--argjson
jq --arg key "$rulesTypeKey" --argjson total "$totalRules"
'.rules.active[$key] = $total'
如果$totalRules
也可能产生原始文本(例如,在边缘情况下(,并且您希望将该值存储为字符串,则在读取时保留-r
选项,在设置时使用--arg
:
jq --arg key "$rulesTypeKey" --arg total "$totalRules"
'.rules.active[$key] = $total'
您的参数周围有单引号:
'$path = $totalArg '
因此,shell不会扩展变量,并且jq
看到未定义的文本字符串$path
。如果使用双引号,则path
和totalArg
都将展开。