【问题标题】:jq - add entry calculated with external commandjq - 添加使用外部命令计算的条目
【发布时间】:2021-03-16 00:56:55
【问题描述】:

我的意见:

{
  "data": [
    {
      "Name": "name 1",
      "Url": "https://some-content.com"
    },
    {
      "Name": "name 2",
      "Url": "https://soming-else.com"
    }
}

我想用curl 检查每个Urlcontent-type 并将其添加到每个对象。所以,我会得到:

{
  "data": [
    {
      "Name": "name 1",
      "Url": "https://some-content.com",
      "ContentType": "video"
    },
    {
      "Name": "name 2",
      "Url": "https://soming-else.com",
      "ContentType": "text"
    }
}

我用来检查content-type响应头值的命令:

curl -sSL <url> -o /dev/null -w '%{content_type}'

我感觉xargs 是正确的方法,但我还没有弄清楚如何以上述方式将其结果添加到输入 JSON。

我也知道 jq 的=| 运算符,但我不知道如何在其中得到xrags 的结果。

我的问题有解决方案吗?可以使用我尝试使用的工具来完成吗?

【问题讨论】:

    标签: curl jq xargs


    【解决方案1】:

    |= 与更新输入的相关性是正确的,我假设它在一个名为 input.json 的文件中

    不幸的是,正如您已经注意到的,jq 不支持“外部”评估,但这里有一种方法,至少是直接的,并且只需要两次调用 jq:

    while read url ; do
        curl -sSL "$url" -o /dev/null -w '%{content_type}'
    done < <(jq -r .data[].Url input.json) | 
    jq -Rn --argfile json input.json '
      [inputs] as $in
      | $json
      | .data |= reduce range(0;length) as $i (.;
                   .[$i].ContentType = $in[$i])
    '
    

    【讨论】:

      【解决方案2】:

      创建内容类型数组并将其合并回原始 JSON:

      jq '.data[].Url' input.json |\
      xargs -n1 curl -sSL -o /dev/null -w '%{content_type}\n' |\
      jq --slurp --raw-input 'split("\n")[:-1] | map({"Content-Type": .})' |\
      jq -n --argfile in1 input.json --argfile in2 /dev/stdin '$in1 | .data |= ([., $in2] | transpose| map(add))'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-08
        • 2014-06-07
        相关资源
        最近更新 更多