我有一個腳本
#!/bin/bash
#create path to redirect output.json to same directory as output.txt
path=$(dirname $1)
#create variables for name line, test lines and result line
firstline=$(cat $1 | head -n 1 | cut -d "[" -f2 | cut -d "]" -f1)
testname=$(echo $firstline)
tests=$(cat $1 | tail -n 3 | head -n -2)
results=$(cat $1 | tail -n1)
#create main JSON variable
json=$(jq -n --arg tn "$testname" '{testname:$tn,tests:[],summary:{}}')
#test's names, status, duration and updating JSON variable
IFS=$'\n'
for i in $tests
do
if [[ $i == not* ]]
then
stat=false
else
stat=true
fi
if [[ $i =~ expecting(. ?)[0-9] ]]
then
var=${BASH_REMATCH[0]}
name=${var%,*}
fi
if [[ $i =~ [0-9]*ms ]]
then
test_duration=${BASH_REMATCH[0]}
fi
json=$(echo $json | jq \
--arg na "$name" \
--arg st "$stat" \
--arg dur "$test_duration" \
'.tests = [{name:$na,status:$st|test("true"),duration:$dur}]')
done
#final success, failed, rating, duration and finishing JSON variable
IFS=$'\n'
for l in $results
do
if [[ $l =~ [0-9] ]]
then
success=${BASH_REMATCH[0]}
fi
if [[ $l =~ ,.[0-9] ]]
then
v=${BASH_REMATCH[0]}
failed=${v:2}
fi
if [[ $l =~ [0-9] .[0-9] % ]] || [[ $l =~ [0-9] % ]]
then
va=${BASH_REMATCH[0]}
rating=${va%%%}
fi
if [[ $l =~ [0-9]*ms ]]
then
duration=${BASH_REMATCH[0]}
fi
json=$(echo $json | jq \
--arg suc "$success" \
--arg fa "$failed" \
--arg rat "$rating" \
--arg dur "$duration" \
'.summary = {success:$suc|tonumber,failed:$fa|tonumber,rating:$rat|tonumber,duration:$dur}')
done
#redirect variable's output to file
echo $json | jq "." > $path"/output.json"
Output.json 看起來像:
{
"testname": "Behave test",
"tests": [
{
"name": "some text",
"status": true,
"duration": "7ms"
},
{
"name": "some text",
"status": false,
"duration": "27ms"
}
],
"summary": {
"success": 1,
"failed": 1,
"rating": 50,
"duration": "34ms"
}
}
輸出比我上面的例子要多得多。我的問題是,我如何計算“匯總”值并將其放入 json?
- “成功” - 狀態為真的測驗;
- “失敗” - 狀態為假的測驗;
- "rating" - 成功/總數,可以是浮點數或整數
- “持續時間” - “持續時間”欄位的總和
我將非常感謝您的幫助。
uj5u.com熱心網友回復:
這會添加(或替換)一個.summary欄位,該欄位是通過reduce將.tests陣列添加到一個物件來計算的,初始化為{success: 0, failed: 0}. 對于每個陣列項,要么遞增,.success要么.failed遞增,具體取決于當前陣列項的布爾.state欄位。該.rating欄位無條件遞增,從而計算專案總數,稍后用于計算真實評分。至于持續時間,陣列項的.duration欄位通過去掉ms后綴轉換為數字,并添加到摘要的(數字).duration欄位中。減少后,通過將成功計數除以它來糾正評級(100為了方便起見,乘以)。該? // 0部分捕獲除以零的問題,以防萬一.tests陣列為空。最后,該.duration欄位重新配備ms后綴。
.summary = (reduce .tests[] as $t ({success: 0, failed: 0};
(if $t.status then .success else .failed end, .rating) = 1
| .duration = ($t.duration | rtrimstr("ms") | tonumber)
) | .rating = (100 * (.success / .rating)? // 0) | .duration |= "\(.//0)ms")
{
"testname": "Behave test",
"tests": [
{
"name": "some text",
"status": true,
"duration": "7ms"
},
{
"name": "some text",
"status": false,
"duration": "27ms"
}
],
"summary": {
"success": 1,
"failed": 1,
"rating": 50,
"duration": "34ms"
}
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/527939.html
標籤:json重击jq
