shell 上传文件,并解析返回的json支持嵌套

85 阅读1分钟
#!/bin/bash

# 自定义处理json function
function get_json(){
echo "$1" | awk -F"[,:}]" '{for(i=1;i<=NF;i++){if($i~/'$2'\042/){print $(i+1)}}}' | tr -d '"' | sed -n '1'p
}
function deal_response(){
        cmd="$1"
        #echo ${cmd} # 打印
        api_result=`eval ${cmd}` # 执行cmd,拿到返回的结果
        #echo ${api_result} # 打印
        value=$(get_json "${api_result}" "$2") # 从api_result中获取json key对应的值
        echo ${value}
}

attachment_id=`deal_response "curl --location 'http://127.0.0.1/storage/file-storage/file-upload' \
--form 'file=@\"/export/320600.json\"'" "attachmentId"`

echo "$attachment_id"
echo "RUNTIME_VAR[attachmentId]=$attachment_id"