使用jq根据字段从对象列表中过滤出一个对象

时间:2019-12-24 13:33:16

标签: json jq

我们有以下json文件,其中包括分区和分区id)

在文件中,我们有6个分区,而所有分区上的主题名称均相同

more file.json

{
  "version": 1,
  "partitions": [
    {
      "topic": "list_of_cars",
      "partition": 2,
      "replicas": [
        1003,
        1004,
        1005
      ],
      "log_dirs": [
        "any",
        "any",
        "any"
      ]
    },
    {
      "topic": "list_of_cars",
      "partition": 4,
      "replicas": [
        1005,
        1006,
        1001
      ],
      "log_dirs": [
        "any",
        "any",
        "any"
      ]
    },
    {
      "topic": "list_of_cars",
      "partition": 0,
      "replicas": [
        1001,
        1002,
        1003
      ],
      "log_dirs": [
        "any",
        "any",
        "any"
      ]
    },
    {
      "topic": "list_of_cars",
      "partition": 1,
      "replicas": [
        1002,
        1003,
        1004
      ],
      "log_dirs": [
        "any",
        "any",
        "any"
      ]
    },
    {
      "topic": "list_of_cars",
      "partition": 5,
      "replicas": [
        1006,
        1001,
        1002
      ],
      "log_dirs": [
        "any",
        "any",
        "any"
      ]
    },
    {
      "topic": "list_of_cars",
      "partition": 3,
      "replicas": [
        1004,
        1005,
        1006
      ],
      "log_dirs": [
        "any",
        "any",
        "any"
      ]
    }
  ]
}

是否可以根据分区ID打印以下内容

例如

让我们说我们要为分区ID – 4打印json部分

那么预期结果应该是这样

{
           "topic": "list_of_cars",
           "partition": 4,
           "replicas": [
                          1005,
                          1006,
                          1001
           ],
           "log_dirs": [
                          "any",
                          "any",
                          "any"
           ]
}

最好的情况是打印以下有效格式(如果可能的话)

{
    "version": 1,
    "partitions": [{
        "topic": "list_of_cars",
        "partition": 4,
        "replicas": [
            1005,
            1006,
            1001
        ],
        "log_dirs": [
            "any",
            "any",
            "any"
        ]
    }]
}

1 个答案:

答案 0 :(得分:3)

这是jq中的简单过滤器,用于从对象列表中选择所需的对象。

jq --arg part_id "4" '.partitions[] | select(.partition == ($part_id|tonumber))'

或使用map()函数

您可以输入所需的分区ID作为输入,然后在select(..)表达式中使用它。由于默认情况下args被评估为字符串,并且过滤器需要检查整数值,因此我们使用tonumber进行了字符串到输入的转换,因此将.partitition与整数值进行比较。 / p>

要回答后续问题以仅保留所需的对象并删除其他对象,请使用|=运算符并选择

jq --arg part_id "4" '.partitions |= map(select(.partition == ($part_id|tonumber)))'