我试图以json格式从API中提取变量,然后将它们重新组合在一起,更改一个变量并将其作为put放回。
唯一的问题是每个值都有引号,并且必须返回到仅用逗号分隔的API。
应该在编辑信息中看到的内容示例,**中的变量:
curl -skv -u redacted:redacted -H Content-Type: application/json -X PUT -d'{properties:{basic:{request_rules:[**"/(req) testrule","/test-body","/(req) test - Admin","test-Caching"**]}}}' https://x.x.x.x:9070/api/tm/1.0/config/active/vservers/xxx-xx
显然,如果我将它们作为普通数组激发,我会得到空格而不是逗号。但是我尝试将其输出为普通字符串
longstr=$(echo ${valuez[@]})
output=$(echo $longstr |sed -e 's/" /",/g')
由于bash被解释的方式,似乎要么解释引号错误或其他原因。我猜这可能是在PUT -d之后封装的单个刻度,但是我不确定如何将变量抛出到具有单个刻度的内容中。
如果我手动放入原始数据,它的工作方式就是变量的发送方式或单个滴答。我没有收到错误,当我回应它时,它看起来很完美。
有什么想法吗?
答案 0 :(得分:0)
如果你有支持FPAT的版本4及更高版本的gnu awk
output=$(echo $longstr |awk '$1=$1' FPAT="(\"[^\"]+\")" OFS=",")
答案 1 :(得分:0)
valuez=( "/(req) testrule" "/test-body" "/(req) test - Admin" "test-Caching" )
csv="" sep=""
for v in "${valuez[@]}"; do csv+="$sep\"$v\""; sep=,; done
echo "$csv"
"/(req) testrule","/test-body","/(req) test - Admin","test-Caching"
如果这是你需要重复做的事情,但它是一个功能:
toCSV () {
local csv sep val
for val; do
csv+="$sep\"$val\""
sep=,
done
echo "$csv"
}
csv=$(toCSV "${valuez[@]}")
答案 2 :(得分:0)
valuez=( "/(req) testrule" "/test-body" "/(req) test - Admin" "test-Caching" )
# Temporarily set IFS to some character which is known not to appear in the array.
oifs=$IFS
IFS=$'\014'
# Flatten the array with the * expansion giving a string containing the array's elements separated by the first character of $IFS.
d_arg="${valuez[*]}"
IFS=$oifs
# If necessary, quote or escape embedded quotation marks. (Implementation-specific, using doubled double quotes as an example.)
d_arg="${d_arg//\"/\"\"}"
# Substitute the known-to-be-absent character for the desired quote+separator+quote.
d_arg="${d_arg//$'\014'/\",\"}"
# Prepend and append quotes.
d_arg="\"$d_arg\""
# insert the prepared arg into the final string.
d_arg="{properties:{basic:{request_rules:[${d_arg}]}}}"
curl ... -d"$d_arg" ...