【问题标题】:How to handle errors in parsing the curl response using jq如何处理使用 jq 解析 curl 响应时出现的错误
【发布时间】:2019-01-02 23:24:22
【问题描述】:
   local response=response.json
    local status=$(curl -s -w %{http_code} "http://www.google.com" -o $response)

    local name=$(cat $response | jq -r .name)
    local address=$(cat $response | jq -r .address)
    if [ $status  = 200 ] && [ $name = "John" ]; then
       # Process response
    else
       # Error
    fi

我正在使用上述方法处理更多请求。在上述情况下,所有请求都失败

如果 URL 无效,则 response.json 不可用。当我解析 $response 2 次时,我收到错误如下 2 次​​p>

response.json not found, No such file or directory
response.json not found, No such file or directory

如何使用 curl 和 jq 以更好的方式处理这些类型的错误?

【问题讨论】:

  • 为什么不直接测试是否创建了response.json? (我会先 mv response.json 如果它存在,以便人们可以更轻松地检查它是否已创建。)
  • 如何以及在哪里检查?
  • 请阅读 bash,尤其是 iftest

标签: bash shell curl jq


【解决方案1】:

怎么样:

if [ $status  = 200 ]; then
  if [ -f $response ]; then
    local name=$(cat $response | jq -r .name)
    if [ $name = "John" ]; then
      local address=$(cat $response | jq -r .address)
      # Process response
    else
      # Error name is not John
    fi
  else
    # Error no response file
  fi
else
   # Error status not 200
fi

您可以添加更多条件 - 键“name”存在,“address”存在,...如果您不想处理错误,只需删除 else 部分

【讨论】:

  • 有没有更好的方法来代替多个 if 语句。
  • 如果要处理这样的决策树逻辑,恐怕没有更好的办法了。另一种方法是将stderr重定向到/dev/null :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-12
  • 2019-05-01
相关资源
最近更新 更多