使用 application/json 時轉義在curl資料中傳送的字串

使用 application/json 時轉義在curl資料中傳送的字串

我正在使用 CURL 發送 JSON 資料。這是一個例子:

mycomputer$ curl -H "Content-Type: application/json" 
     -d  "{ "some_string": "Hello mom it's me!" }"
     "http://localhost:3001/api_v2/blocks/42af6ab04d9d9635a97f8abec14ed023?api_key=fe5cf0d86af27c086ab5cd4d0eab6641"

如何轉義任何值的內容some_string

例如,如果有人想放入字串,Abe Lincoln's favorite character is the backslash \. He said "I love the \ and single quotes like ''".我如何在使用curl時轉義它?

我想我需要做以下事情:

  • 如果字串包含"轉義符,則使用三個反斜線\\\"

  • 如果字串包含'轉義符,則不需要轉義'

  • 如果字串包含\轉義符,則使用三個反斜線\\\\

有沒有我忘記的角色?

答案1

我假設您的目標只是讓字串通過 shell 的解析。如果是這樣,請使用read

例如

$ IFS='' read -r var

然後手動貼上該線。

如果是多行,您可以使用:

$ IFS='' read -r -d '' var

並再次貼上,但這次使用CTRL+d結束輸入。

或使用定界符:

$ IFS='' read -r -d '' var <<'EOF'
{ "some_string": "Hello mom it's me!" }
EOF

 

無論您使用哪種方法,您都可以使用該變數$var來存取它:

$ curl -H "Content-Type: application/json" \
 -d  "$var" \
 "http://localhost:3001/api_v2/blocks/42af6ab04d9d9635a97f8abec14ed023?api_key=fe5cf0d86af27c086ab5cd4d0eab6641"

答案2

如果您可以從等式中刪除外殼,您可能不需要其中的 3 個反斜線。幸運的是,您可以:

curl --config - <<\DATA
    url    = "http://some.url"
    header = "Content-Type: application/json"
    data   = "{ \"some_string\": "Abe Lincoln's favorite character is the backslash \\. He said \"I love the \\ and single quotes like '.\""
#END
DATA

看著man curl。我建議密切注意之間的差異--data-ascii (就是這個-d意思)--data-binary, 和--data-urlencoded

您可能還想比較使用 、 和 獲得的--header不同--data行為--form (預設情況下,它們的執行POST方式略有不同),以及您可能得到的內容--get,可以將前面提到的任何指定的資料編碼到?.

答案3

考慮使用 JSON 感知工具來建立 JSON 文件。

使用jq

json=$(
    jq -n --arg 'Some key "string"' "My cat's useless" '$ARGS.named'
)

使用jo

json=$( jo 'Some key "string"'="My cat's useless" )

請注意,jo如果鍵的值以 結尾,則會嘗試推斷該值是陣列條目[]

對於上述程式碼的兩種變體,json變數將獲得相當於

{
  "Some key \"string\"": "My cat's useless"
}

然後,您可以json在呼叫中使用該變數curl

curl -H 'Content-Type: application/json' \
    -d "$json" \
    'http://localhost:3001/api_v2/some/endpoint'

相關內容