【问题标题】:jq get multiple values from different [] at once with jqjq 使用 jq 一次从不同的 [] 获取多个值
【发布时间】:2018-03-07 21:07:57
【问题描述】:

在 [] 中有很多下面的块,如何提取 .eye.four.watcher1[].name=="cat" 的 .title 和 "value" 对于具有 "group": "A" 的块?

我已经尝试过的是:

$jq'. |选择(.group=="A") | .title +" "+.eye.four.watcher1[].name' test.json

“ProfileXXX 狗”

“ProfileXXX 猫”

“ProfileXXX 鼠标”

但是如何只打印带有“group”的块的“cat”的titt和value:“A”,?

{
  "title": "ProfileXXX",
  "pagelen": 10,
  "group": "A",
  "size": 1,
  "eye": {
    "one": "git",
    "two": false,
    "three": "...",
    "four": {
      "watcher1": [
        {
          "name": "dog",
          "value": "aaaa"
        },
        {
          "name": "cat",
          "value": "bbbb"
        },
        {
          "name": "mouse",
          "value": "cccc"
        }
      ],
      "watcher2": {
        "type": "B",
        "href": "2..."
      },
      "watcher3": {
        "type": "C",
        "href": "3..."
      },
      "values": [
        {
          "five": "git",
          "six": false,
          "seven": "...",
          "eight": {
            "watchers": {
              "href": "..."
            },
            "forks": {
              "href": "..."
            },
            "clone": [
              {
                "href": "...",
                "name": "https"
              },
              {
                "href": "...",
                "name": "ssh"
              }
            ],
            "pullrequests": {
              "href": "..."
            }
          },
          "fourteen": false,
          "fiveteen": {
            "username": "...",
            "display_name": "...",
            "uuid": "...",
            "links": {
              "self": {
                "href": "..."
              },
              "html": {
                "href": "..."
              },
              "avatar": {
                "href": "..."
              }
            }
          },
          "updated_on": "...",
          "size": 2328936,
          "is_private": true,
          "uuid": "..."
        }
      ]
    }
  }
}

【问题讨论】:

    标签: jq


    【解决方案1】:

    jq解决办法:

    jq -r '.[] | select(.group=="A") | .title +" "+ (.eye.four.watcher1[] | select(.name=="cat")).value' test.json
    

    输出:

    ProfileXXX bbbb
    

    【讨论】:

      【解决方案2】:

      这是一个使用variable bindingstring interpolation的解决方案:

           select(.group == "A")
         | .title as $t
         | .eye.four.watcher1[]
         | select(.name == "cat")
         | "\($t) \(.value)"
      

      使用filter.jq 中的过滤器和test.json 中的样本数据

      $ jq -Mr -f filter.jq test.json
      

      生产

      ProfileXXX bbbb
      

      Try it online!

      【讨论】:

        猜你喜欢
        • 2023-01-27
        • 2017-01-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多