我有这样的卷曲请求:
curl -s -u $user:$password -X GET -H "Content-Type: application/json" $url
返回json作为响应。所以我将使用jq解析响应以获取一些特定数据。像这样:
curl -s -u $user:$password -X GET -H "Content-Type: application/json" $url | jq '<expression>'
现在,如果curl请求失败,那么解析操作显然会引发丑陋的错误。我想避免这种情况。如何请求首先存储响应,然后在请求成功时解析它。我不想显示json整个响应。此外,如果我在请求中添加-w "%{http_code}"
,则会将状态代码附加到JSON响应中,这会影响解析。怎么解决这个?我基本上想先检查curl请求是否成功,然后获取JSON响应并解析它。我还想获取状态代码,这样如果失败,我可以显示状态代码。但状态代码现在搞乱了json的反应。
答案 0 :(得分:2)
您可以合并--write
和--fail
选项:
# separating the (verbose) curl options into an array for readability
curl_args=(
--write "%{http_code}\n"
--fail
--silent
--user "$user:$password"
--request GET
--header "Content-Type: application/json"
)
if ! output=$(curl "${curl_args[@]}" "$url"); then
echo "Failure: code=$output"
else
# remove the "http_code" line from the end of the output, and parse it
sed '$d' <<<"$output" | jq '...'
fi
另请注意:quote your variables!
答案 1 :(得分:0)
我发现glenn jackman的答案很好,但有点令人困惑,所以我重新编写了它,并对其进行了修改,以便我可以将其用作curl | jq
的更安全的替代品。
#!/bin/bash
# call this with normal curl arguments, especially url argument, e.g.
# safecurl.sh "http://example.com:8080/something/"
# separating the (verbose) curl options into an array for readability
curl_args=(
-H 'Accept:application/json'
-H 'Content-Type:application/json'
--write '\n%{http_code}\n'
--fail
--silent
)
echo "${curl_args[@]}"
# prepend some arguments, but pass on whatever arguments this script was called with
output=$(curl "${curl_args[@]}" "$@")
return_code=$?
if [ 0 -eq $return_code ]; then
# remove the "http_code" line from the end of the output, and parse it
echo "$output" | sed '$d' | jq .
else
# echo to stderr so further piping to jq will process empty output
>&2 echo "Failure: code=$output"
fi
注意:此代码不测试忽略请求的内容类型并使用HTML响应的服务。您需要为此测试grep -l '</html>'
。