1
如何轉換文本字符串,並將其添加到現有的JSON對象JQ轉換文本字符串,並將其添加到現有的JSON對象
當前JSON輸出:
{
"start process": "Wed May 24 05:22:35 UTC 2017",
"logfilename": "log_test"
}
{
"start filelist": [
"/downloads/json_log_array2object.jq",
"/downloads/json_log_string2object.jq",
"/downloads/log_test.json",
"/downloads/log_test.txt",
"/downloads/test_logs.sh"
]
}
目標JSON輸出:
{
"start process": "Wed May 24 05:22:35 UTC 2017",
"logfilename": "log_test",
"start filelist": [
"/downloads/json_log_array2object.jq",
"/downloads/json_log_string2object.jq",
"/downloads/log_test.json",
"/downloads/log_test.txt",
"/downloads/test_logs.sh"
]
}
bash腳本:
logfilename="log_test"
writelogstring2object() {
exec 4>>"${1}.json"
flock -x 4
tee -a "$1.txt" | jq -sRf json_log_string2object.jq >&4
}
writelogarray2object() {
exec 4>>"${1}.json"
flock -x 4
tee -a "$1.txt" | jq -nRf json_log_array2object.jq >&4
}
exec 3> >(writelogstring2object "$logfilename")
{
echo "start process: $(date -u)"
echo "logfilename:" $logfilename
} >&3
exec 3>&-
flock -s "$logfilename.json" -c :
exec 3> >(writelogarray2object "$logfilename")
{
echo "start filelist:"
printf '%s\n' "$PWD"/*
} >&3
exec 3>&-
flock -s "$logfilename.json" -c :
JQ方案:
json_log_string2object.jq
def trim: sub("^ +";"") | sub(" +$";"");
def s2o:
(index(":") // empty) as $ix
| {(.[:$ix]): (.[$ix+1:]|trim)};
split("\n") | map(s2o) | add
json_log_array2object.jq
foreach (inputs,null) as $line ({};
if $line == null then .emit = {(.key|tostring): .value}
elif $line[-1:] == ":"
then (if .key then {emit: {(.key): .value}} else null end)
+ { key : $line[0:-1] }
else {key, value: (.value + [$line])}
end;
.emit // empty)
欣賞方法和實例
謝謝你,很好地添加這兩個對象,實現爲一個函數。你將如何刪除以前的對象?或者可能的解決方案是在創建下一個對象時包含添加,以便在日誌中只創建一個對象? – Gabe
嘗試執行,以便'writelogarray2object()'將文件描述符JSON對象添加到日誌文件JSON對象。但認爲這只是一個部分解決方案,因爲它仍然會向日志文件寫入另一個「添加」對象。試圖避免將日誌文件中的JSON對象後處理成單個JSON對象日誌文件,但不知道該怎麼辦? – Gabe