jq过滤器:通过选择显示整个结构

jq过滤器:通过选择显示整个结构

我有以下 file1 json:

{
  "name": "eye",
  "attributes": [
    {
      "name": "Width",
      "value": "1920"
    },
    {
      "name": "Height",
      "value": "1080"
    },
    {
      "name": "WinKeyMapping",
      "value": "leftwin"
    }
  ],
  "starts": [
    {
      "name": "step1",
      "attributeList": [
        {
          "name": "Command",
          "value": "bash"
        },
        {
          "name": "Test",
          "value": "none"
        }
      ]
    }
  ]
}

和以下过滤器:

$ jq '.starts[].attributeList[]|select(.name=="Command")' file1
{
  "name": "Command",
  "value": "bash"
}
$

我怎样才能获得这个选择的完整结构?

预期输出:

{
  "starts": [
    {
      "attributeList": [
        {
          "name": "Command",
          "value": "bash"
        }
      ]
    }
  ]
}

答案1

直接与jq:

jq '{ starts: [ { attributeList: (.starts[].attributeList 
                                  | map(select(.name == "Command"))) }] }' file.json

输出:

{
  "starts": [
    {
      "attributeList": [
        {
          "name": "Command",
          "value": "bash"
        }
      ]
    }
  ]
}

答案2

以下是获得所需输出的两个选项。

您可以删除不需要的键:

jq 'del(.attributes, .name) | 
  .starts[].attributeList = map(.[].attributeList[] | select(.name == "Command"))'

或者您可以只选择您想要的键:

jq 'to_entries | map(select(.key == "starts")) | from_entries | 
  .starts[].attributeList = map(.[].attributeList[] | select(.name == "Command"))'

两者给出相同的结果。另外,如果您愿意starts,并且ends在后一种情况下,您可以添加其他or语句:map(select((.key == "starts") or (.key == "ends")))

答案3

更通用的方法是jq

def pick_out(q): path(q) as $path | ($path | length) as $length |
    delpaths(
        [
            paths(..) |
            select(length <= $length and $path[0:length] != . )
        ]
    );

这是一个jq函数,用于删除不在给定参数(可能是一个调用)路径上任何位置的文档的所有路径select()

将其保存在 中pick_out.jq,我们可以像这样使用它:

jq 'include "pick_out";
    pick_out(
        .starts[].attributeList[] | select(.name == "Command")
    )' file.json

输出:

{
  "starts": [
    {
      "attributeList": [
        {
          "name": "Command",
          "value": "bash"
        }
      ]
    }
  ]
}

相关内容