仅将最后一个变量设置为文件
在bash中使用jq来解析json。
for currentActivation in ${ACTIVATION_ARRAY[@]}; do
rulesResponse=$(curl -s -XGET "$RULES_REQUEST_URL_PREFIX&activation=$currentActivation&types=$rulesTypeKey&p=1&ps=1")
typeRuleTotal=$(jq -r '.total' <<< "$rulesResponse")
echo "current_rulesTypeKey = $rulesTypeKey, typeRuleTotal = $typeRuleTotal"
jq --argjson totalArg "$typeRuleTotal" --arg currentType "$rulesTypeKey" '.rules.active[$currentType] = $totalArg ' <<<$RULES_REPORT_INIT_JSON >$FILE_REPORT_RULES
done
这里的输出:
current_rulesTypeKey = CODE_SMELL, typeRuleTotal = 310
current_rulesTypeKey = SECURITY_HOTSPOT, typeRuleTotal = 1
current_rulesTypeKey = BUG, typeRuleTotal = 304
current_rulesTypeKey = VULNERABILITY, typeRuleTotal = 120
但是在文件 $FILE_REPORT_RULES 上仅保存了最后一个值 = 120 :
{
"rules": {
"totalActive": 0,
"totalInactive": 0,
"active": {
"BUG": 0,
"VULNERABILITY": 120,
"CODE_SMELL": 0,
"SECURITY_HOTSPOT": 0
}
}
}
In bash use jq to parse json.
for currentActivation in ${ACTIVATION_ARRAY[@]}; do
rulesResponse=$(curl -s -XGET "$RULES_REQUEST_URL_PREFIX&activation=$currentActivation&types=$rulesTypeKey&p=1&ps=1")
typeRuleTotal=$(jq -r '.total' <<< "$rulesResponse")
echo "current_rulesTypeKey = $rulesTypeKey, typeRuleTotal = $typeRuleTotal"
jq --argjson totalArg "$typeRuleTotal" --arg currentType "$rulesTypeKey" '.rules.active[$currentType] = $totalArg ' <<<$RULES_REPORT_INIT_JSON >$FILE_REPORT_RULES
done
And here output:
current_rulesTypeKey = CODE_SMELL, typeRuleTotal = 310
current_rulesTypeKey = SECURITY_HOTSPOT, typeRuleTotal = 1
current_rulesTypeKey = BUG, typeRuleTotal = 304
current_rulesTypeKey = VULNERABILITY, typeRuleTotal = 120
But on file $FILE_REPORT_RULES saved only last value = 120 :
{
"rules": {
"totalActive": 0,
"totalInactive": 0,
"active": {
"BUG": 0,
"VULNERABILITY": 120,
"CODE_SMELL": 0,
"SECURITY_HOTSPOT": 0
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您按顺序写入同一个文件,但始终使用未更改的输入
$RULES_REPORT_INIT_JSON
。这使您只能看到最后的更改。您可以保存对变量的更改并在最后写入文件一次,而不是在每次迭代时写入文件:
或者,如果
$RULES_REPORT_INIT_JSON
需要在整个循环中保持不变,请使用而是一个临时变量You are sequentially writing to the same file but always using the unaltered input
$RULES_REPORT_INIT_JSON
. This makes you see only the last change.Instead of writing to the file on each iteration, you could save the changes to the variable and write to the file just once in the end:
Or, if
$RULES_REPORT_INIT_JSON
needs to stay unaltered throughout the loop, use a temporary variable instead