首页 > 解决方案 > 对参数定义的 JSON 进行 PUT 调用

问题描述

我有一个这样的脚本,其中“get_customers”是我的预定义函数,我必须将以下四个值中的每一个作为参数传递给所有客户的 PUT 调用。但是,我在运行此程序时收到错误 HTTP 400 Bad Request)","error":"ERROR_BAD_REQUEST"。有人知道我如何在 PUT 调用中使用这个 for 循环传递 JSON 正文吗?我的脚本错了吗?

name=($(get_customers | jq --raw-output '.values[].name'))
tenantId=($(get_customers | jq --raw-output '.values[].tenantId'))
nodeId=($(get_customers | jq --raw-output '.values[].nodeId'))
d=($(get_customers | jq --raw-output '.values[].id'))

for (( i=0; i<${#name[@]}; i++ )); do
        
    
    curl -X PUT --header "Content-Type: application/json" --header "Accept: application/json" --header "Authorization: Bearer ${API_TOKEN}" -d '{"id":"${d[i]}","name":"${name[i]}","tenantId":"${tenantId[i]}","nodeId":"${nodeId[i]}"}'  -k "${URL}/api/file/files/${d[i]}"
    
    

done

标签: bashput

解决方案


您正在使用单引号,其中变量未扩展。尝试这个:

for (( i=0; i<${#name[@]}; i++ )); do
    curl -X PUT --header "Content-Type: application/json"\
                --header "Accept: application/json"\
                --header "Authorization: Bearer ${API_TOKEN}"\
         -d "$(cat << EOF
{"id":"${d[i]}","name":"${name[i]}","tenantId":"${tenantId[i]}","nodeId":"${nodeId[i]}"}
EOF
)" -k "${URL}/api/file/files/${d[i]}"
done

推荐阅读