jq使用jq一次从不同的[]中获取多个值

时间:2017-09-26 15:00:40

标签: jq

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

的块

我尝试过的是:

$ jq'。 |选择(.group ==" A")| .title +" "。+ eye.four.watcher1 []名称&#39。 test.json

" ProfileXXX dog"

" ProfileXXX cat"

" ProfileXXX鼠标"

但是如何只打印" cat"的标题和价值?使用" group":" 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": "..."
        }
      ]
    }
  }
}

2 个答案:

答案 0 :(得分:2)

jq 解决方案:

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

输出:

ProfileXXX bbbb

答案 1 :(得分: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!