我有一個關聯陣列,我想將它作為 POST 資料傳遞給 cURL。但是我嘗試了多種方法,但它仍然不起作用。
陣列:_
declare -A details
details[name]="Honey"
details[class]="10"
details[section]="A"
details[subject]="maths"
到目前為止,cURL 命令已經嘗試過(所有這些都失敗了):
resp = $(cURL --request POST --data details "https://somedomain.net/getMarks")
resp = $(cURL --request POST --data variables=details "https://somedomain.net/getMarks")
resp = $(cURL --request POST --data "variables=$details" "https://somedomain.net/getMarks")
resp = $(cURL --request POST --data "variables=${details}" "https://somedomain.net/getMarks")
resp = $(cURL --request POST --data $details "https://somedomain.net/getMarks")
resp = $(cURL --request POST --data ${details} "https://somedomain.net/getMarks")
resp = $(cURL --request POST --data variables=details "https://somedomain.net/getMarks")
如下所示,我希望(間接地)上述請求,但是我想直接傳遞陣列而不是寫入其內容。
resp = $(cURL --request POST --data '{"variables":[{"name": "Honey"},{"class": "10"},{"section": "A"},{"subject": "maths"}]}' "https://somedomain.net/getMarks")
請注意,首先我將始終只有關聯陣列(不是任何 json 陣列或字串)。
當我嘗試使用此鏈接(GITLAB API)上的關聯陣列呼叫 cURL 命令時,這個問題出現了(該示例不包含變數陣列示例)。在這里,他們提到了一個變數陣列(哈希陣列)。
uj5u.com熱心網友回復:
- 由于我必須使用舊版本的 bash,它不涉及答案中所述的名稱參考,因此我不得不嘗試撰寫關聯陣列的字串創建而不將其傳遞給函式
- 由于我總是有一個以 開頭的關聯陣列,因此傳遞 gitlab API 接受的陣列的程序通常是:
resp=$(cURL --request POST --data '{"variables":[{"name": "Honey"},{"class": "10"},{"section": "A"},{"subject": "maths"}]}' "https://somedomain.net/getMarks")
或者
resp=$(cURL --request POST --data "variables[name]=Honey" --data "variables[class]=10" --data "variables[section]=A" --data "variables[subject]=maths" "https://somedomain.net/getMarks")
所以嘗試了第二種方式的一些調整,對我有用的是:
_sep=""
_string=""
for index in "${!details[@]}"
do
_string="${_string}${_sep}variables[${index}]="${details[$index]}"
_sep="&"
done
resp=$(cURL --request POST --data "$_string" "https://somedomain.net/getMarks")
#which indirectly was:
resp=$(cURL --request POST --data "variables[name]=Honey&variables[class]=10&variables[section]=A&variables[subject]=maths" "https://somedomain.net/getMarks")
這是成功的。感謝@markp-fuso 讓我直觀地用上面的邏輯創建了一個字串。
uj5u.com熱心網友回復:
假設/理解:
- 無需以任何特定順序列出陣列條目
- 陣列索引或值都不包含換行符
一個bash想法:
# use a function to build the --data component
build_data() {
local -n _arr="$1" # use nameref so we can pass in the name of any associative array
local _sep=""
local _string='{"variables":['
local _i
for i in "${!_arr[@]}"
do
_string="${_string}${_sep}{\"${i}\": \"${_arr[$i]}\"}"
_sep=","
done
printf "%s]}" "${_string}"
}
將此添加到curl通話中:
resp=$(cURL --request POST --data "$(build_data details)" "https://somedomain.net/getMarks")
筆記:
- 的兩邊都不允許有空格
=,即,resp = $(curl ...)必須是resp=$(curl ...) - 沒有實際/有效的 URL,我猜測轉義引號是否/在哪里,因此可能需要調整轉義引號才能正常作業
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/530141.html
下一篇:如何在一項活動中制作多個抽屜布局
