首页 > 解决方案 > 使用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"
        ]
    }]
}

标签: jsonjq

解决方案


这是一项简单的过滤工作,jq可以从对象列表中选择所需的对象。

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

或使用该map()功能

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

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

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

推荐阅读