linux 需要帮助来修复shell脚本以将字符串转换为json响应

o75abkj4  于 2023-03-07  发布在  Linux
关注(0)|答案(3)|浏览(178)

我正在尝试转换下面的字符串是存储在一个txt文件到json格式的字符串

High Severity Results: 0
Medium Severity Results: 1
Low Severity Results: 2
Information Severity Results: 0
Scan Results Location: Https://www.checkmarx.abc.com/cxwebclient/viewermain.aspx?scanid=12345&projectid=1234

到json格式以下

{
"High Severity Results" : "0",
"Medium Severity Results" : "1",
"Low Severity Results" : "2",
"Information Severity Results" : "0",
"Scan Results Location" : "Https://www.checkmarx.abc.com/cxwebclient/viewermain.aspx?scanid=12345&projectid=1234",
}

我尝试了以下命令。

file="Checkmarx_Json_Data.txt"
checkmarxDataNew="$(cat Checkmarx_Json_Data.txt)"
while IFS= read -r line || [[ -n "$line" ]]; do
  for val in $line
  do
    echo "\"${val//:/\":\"}\"" >> ACM_BQ_JSON_Response.json
  done
done < "$file"

但上述脚本正在生成以下格式的响应

"checkmarx" : {
"High"
"Severity"
"Results":""
"0"
"Medium"
"Severity"
"Results":""
"1"
"Low"
"Severity"
"Results":""
"2"
"Information"
"Severity"
"Results":""
"0"
"Scan"
"Results"
"Location":""
"Https":"//www.checkmarx.ford.com/cxwebclient/viewermain.aspx?scanid=2500093&projectid=28069"
}

当我尝试用一个像color:red这样的单字符串时,效果很好。
有人能帮我解决这个问题吗?

fruv7luv

fruv7luv1#

下面是使用jq可以实现的方法:

jq --raw-input 'split(" *: +"; "") | { (.[0]): .[1] }' < input-file | jq -s add

输出:

{
  "High Severity Results": "0",
  "Medium Severity Results": "1",
  "Low Severity Results": "2",
  "Information Severity Results": "0",
  "Scan Results Location": "Https://www.checkmarx.abc.com/cxwebclient/viewermain.aspx?scanid=12345&projectid=1234"
}
vc9ivgsu

vc9ivgsu2#

使用sed

$ sed -Ee 's/$/,/;1i\{' -e '$a\}' -e 's/^([^:]*)(: )([^,]*)/"\1" \2"\3"/' Checkmarx_Json_Data.txt
{
"High Severity Results" : "0",
"Medium Severity Results" : "1",
"Low Severity Results" : "2",
"Information Severity Results" : "0",
"Scan Results Location" : "Https://www.checkmarx.abc.com/cxwebclient/viewermain.aspx?scanid=12345&projectid=1234",
}
exdqitrt

exdqitrt3#

#!/usr/bin/env bash

total_cnt=$(wc -l < Checkmarx_Json_Data.txt)

{
printf {\\n
while IFS= read -r line; do
  col1=${line%%:*}
  col2=${line#*: }
  if ((++line_cnt < total_cnt)); then
    printf '  "%s" : "%s",\n' "$col1" "$col2"
  else
    printf '  "%s" : "%s"\n' "$col1" "$col2"
  fi
done < Checkmarx_Json_Data.txt
printf }
} > ACM_BQ_JSON_Response.json

如果ed可用/可接受,则如下所示:
script.ed(根据自己的内心内容命名)

,s/\([^:]*\)\(: \)\(.*\)/  "\1" \2"\3"/
1,$-1s/$/,/
0a
{
.
$a
}
.
,p
Q

现在运行:

ed -s Checkmarx_Json_Data.txt < script.ed

要使用编辑的输出创建新文件,

ed -s Checkmarx_Json_Data.txt < script.ed > ACM_BQ_JSON_Response.json

相关问题