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"
]
}]
}
解决方案
这是一项简单的过滤工作,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)))'
推荐阅读
- spring-security - Spring Oauth2 Client,自动刷新过期的access_token
- pytorch - Pytorch:涉及端到端雅可比范数的自定义损失
- visual-studio - VS2019 - 代码样式 - 在新行上强制执行表达式主体
- c++ - 如何在 C++ 中的“.bin”文件中编写结构数组?
- python - 根据其他列的唯一字符串创建一个带有数字的新列
- c++ - 在 C++ 中使用克隆方法实现多态效果
- haskell - 案例 - 为什么我得到非法的 lambda 表达式
- python - 协程上的 Python asyncio 块,但不是 websockets
- javascript - 更改 scorll 上导航项的活动状态及其一个小问题
- android - 是否可以从我的应用程序内的推送通知中打开链接,而无需将链接先前存储在应用程序内?