curl
スクリプトの本文に複数行のコメントを送信しようとしていますbash
。以下は私のcurl
電話です。
#!/bin/bash
temp="This is sample data: 2019/05/21 03:33:04
This is 2nd sample data: #2 Sample_Data"
response=$(curl -sS --location "${HEADERS[@]}" -w "%{http_code}\n" -X POST "$url" --header 'Content-Type: application/json' \
--data-raw "{
\"id\" : \"111\",
\"status\" : {
.
.
.
\"details\" : [ \"$temp\" ]
}
}")
echo "$response"
実際のスクリプトでは変数がtemp
ですstdout
。したがって、複数行で出力されます。上記のスクリプトを試してみると、次のエラーが発生します。
{"exceptionClass":"xxx.exception.MessageNotReadableException","errorCode":"xxx.body.notReadable","message":"The given request body is not well formed"}400
誰でも問題が何であるか、解決策を教えてもらえますか?
事前にありがとう
ベストアンサー1
JSON文字列にリテラル改行を含めることはできません。まず、変数の値を適切にJSONにエンコードしないと、JSONドキュメントにシェル変数を挿入できません。
文字列をエンコードする1つの方法は、次を使用することですjq
。
status_details=$( jq -n --arg string "$temp" '$string' )
上記のコマンドはシェル変数ではなく$string
内部変数であることに注意してください。jq
このjq
ユーティリティは、コマンドラインで指定された値をエンコード$string
し、それをJSONエンコード文字列として出力します。
サンプルコードが与えられると、status_details
変数は引用符を含む次のリテラル文字列に設定されます。
"This is sample data: 2019/05/21 03:33:04\n This is 2nd sample data: #2 Sample_Data"
その後、通話で使用できますcurl
。
curl -s -S -L -w '%{http_code}\n' -X POST \
--data-raw '{ "id": "111", "status": { "details": [ '"$status_details"' ] } }' \
"$url"
details
配列を使用して各行を別々の要素として保存する場合は、次のように配列に$temp
分割できます。$temp
jq
status_details=$( jq -n --arg string "$temp" '$string | split("\n")' )
これはあなたに次の文字通りの痛みを与えます$status_details
:
[
"This is sample data: 2019/05/21 03:33:04",
" This is 2nd sample data: #2 Sample_Data"
]
curl
その後、上記とほぼ同じ方法で使用できますが、$status_details
角かっこ(... "details": '"$status_details"' ...
)は使用しません。