【问题标题】:Is there a better solution to cURL this JSON?cURL 这个 JSON 有更好的解决方案吗?
【发布时间】:2018-03-13 03:43:08
【问题描述】:

我有这个函数,它使用curljq 作为 JSON 处理器迭代给定 JSON 的键,我的代码如下所示:(bash)

function getJSONContent {
  option=""

  for option in "header" "developer" "category" "description"
  do
    content=$(curl -s $extension_url | jq ".[\"$extension\"][\"$option\"]")
    printf "$content\n"
  done
}

但问题是它卷曲了 4 次,我还没有找到更好的解决方案而不会出错。

这样做可以吗?或者在 Bash / Shellscript 中是否有更好的解决方案?

【问题讨论】:

    标签: json bash for-loop curl jq


    【解决方案1】:

    有没有更好的解决方案...?

    是的!

    1. 你显然只需要一次调用 curl 和一次调用 jq,但在最 至少,您应该避免多次调用 curl。

    2. 避免“即时”构建 jq 命令。相反,您可以传入 shell(或环境)变量 在命令行上,例如使用 --arg 或 --argjson

    3. 在这种特定情况下,您似乎可以通过简单地使用 jq 的 ',' 运算符来避免多次调用 jq。

    简而言之,尝试以下方法:

     curl -s "$extension_url" |
       jq --arg extension "$extension" '
         .[$extension]["header","developer","category","description"]'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 2011-10-18
      • 1970-01-01
      • 2010-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多