在 shell 脚本中使用 JSON 换行符

在 shell 脚本中使用 JSON 换行符

如何在以下代码中使用换行符(在 propertyVar 内)

#!/bin/sh
#Shell script for running the script from Jenkins
#Performance Engineering Team

HealthPollingInterval=$1
ThinkTime=$2
XMLReport=$3
UserDataFile=$4
CdnUrl=$5
StreamingUrl=$6
TrThinkTime=$7
TrMinThinkTime=$8
TrMaxThinkTime=$9
AxThinkTime=$10
AxMinThinkTime=$11
AxMaxThinkTime=$12

triggerPerformanceTest(){
echo "checking the status of the health service"    
HTTP_RESPONSE=$(curl -m 1800 --silent --write-out "HTTPSTATUS:%{http_code}" -X GET http://localhost/health)
HTTP_STATUS=$(echo $HTTP_RESPONSE | tr -d '\n' | sed -e 's/.*HTTPSTATUS://')
HTTP_BODY=$(echo $HTTP_RESPONSE | sed -e 's/HTTPSTATUS\:.*//g')
if [ $HTTP_STATUS -eq 200  ] && [ $HTTP_BODY = "OK" ]; then
    propertyVar='{"HealthPollingInterval": '"$HealthPollingInterval"', "ThinkTime": '"$ThinkTime"', "XMLReport": '\""$XMLReport"\"',\r\n
                "UserDataFile": '\""$UserDataFile"\"',  "CdnUrl": '\""$CdnUrl"\"',  "StreamingUrl": '\""$StreamingUrl"\"',
                "TrThinkTime": '"$TrThinkTime"', "TrMinThinkTime": '"$TrMinThinkTime"', "TrMaxThinkTime": '"$TrMaxThinkTime"',
                "AxThinkTime": '"$AxThinkTime"', "AxMinThinkTime": '"$AxMinThinkTime"', "AxMaxThinkTime": '"$AxMaxThinkTime"'}'
    echo "$propertyVar"
    #curl -X POST http://localhost/triggerExecutionwithParamater -H 'Content-Type: application/json' -d "$propertyVar"
else
    echo "Need to start the service on the target machine"
fi
}
triggerPerformanceTest $HealthPollingInterval $ThinkTime $XMLReport $UserDataFile $CdnUrl $StreamingUrl $TrThinkTime $TrMinThinkTime $TrMaxThinkTime $AxThinkTime $AxMinThinkTime $AxMaxThinkTime

propertyVar 内部有 10-15 个变量,如果我将它们放在一行中,脚本就可以正常工作。但我想使用换行符使它们保持有序。到目前为止,已经使用了 \, \n, "\n" , '\n', \r\n ,但没有任何效果。

答案1

创建有效 JSON 的最简单方法是使用支持 JSON 的工具,例如jq.

以下代码根据脚本的 12 个命令行参数创建 JSON 文档,并使用以下命令发布文档curl

#!/bin/bash

if [ "$#" -ne 12 ]; then
        printf 'Expected 12 arguments, got %d\n' "$#"
        exit 1
fi >&2

args=( "$@" )   # Save the original arguments for later.

# Prepare arguments for "jq".
for param in \
        HealthPollingInterval \
        ThinkTime \
        XMLReport \
        UserDataFile \
        CdnUrl \
        StreamingUrl \
        TrThinkTime \
        TrMinThinkTime \
        TrMaxThinkTime \
        AxThinkTime \
        AxMinThinkTime \
        AxMaxThinkTime
do
        set -- "$@" --arg "$param" "$1"
        shift
done

# Create our JSON document and post it.
# Output an error message and terminate if the post fails.
if ! jq -nc "$@" '$ARGS.named' |
        curl --silent --show-error --fail \
                --json @- 'http://localhost/triggerExecutionwithParamater'
then
        echo 'Failed to post JSON document.' >&2
        exit 1
fi


# Call triggerPerformanceTest with the original arguments.
triggerPerformanceTest "${args[@]}"

这使用循环创建一系列--arg key value稍后与 一起使用的参数jq。该jq调用创建一个包含命名键及其值的 JSON 对象,然后将其通过管道传输curl并发布到 API 端点。

答案2

与@Kusalananda相同,使用perl而不是jq

#! /bin/sh -
perl -CA -MJSON -le '
  $object{$_} = shift @ARGV for qw(
    HealthPollingInterval  ThinkTime         XMLReport
    UserDataFile           CdnUrl            StreamingUrl
    TrThinkTime            TrMinThinkTime    TrMaxThinkTime
    AxThinkTime            AxMinThinkTime    AxMaxThinkTime
  );
  print encode_json(\%object)' -- "$@" |
  curl --silent --show-error --fail \
      --json @- 'http://localhost/triggerExecutionwithParamater'

答案3

你可能想要使用heredoc保留格式, 虽然Heredoc delimeter 必须不带引号才能执行替换

所以在你的情况下 then... 和 ..else 之间的块将是

    read -r -d '' propertyVar <<EOF
        {
            "HealthPollingInterval": "$HealthPollingInterval", "ThinkTime": "$ThinkTime", "XMLReport": "$XMLReport"
            "UserDataFile": "$UserDataFile",  "CdnUrl": "$CdnUrl",  "StreamingUrl": "$StreamingUrl",
            "TrThinkTime": "$TrThinkTime", "TrMinThinkTime": "$TrMinThinkTime", "TrMaxThinkTime": "$TrMaxThinkTime",
            "AxThinkTime": "$AxThinkTime", "AxMinThinkTime": "$AxMinThinkTime", "AxMaxThinkTime": "$AxMaxThinkTime"
        }
    EOF
    echo "$propertyVar"

如果您指定<<'EOF'or <<"EOF",则定界文档内不会进行任何变量替换。

相关内容