bashスクリプトのカール本文に複数行のデータを送信するには?

bashスクリプトのカール本文に複数行のデータを送信するには?

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分割できます。$tempjq

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"' ...)は使用しません。

おすすめ記事