jq语法实现:筛选非free状态节点并输出节点名与注释
解决方法
直接用这条命令就能满足你的需求:
some-command | jq '.nodes | to_entries[] | select(.value.state != "free") | "\(.key): {comment: \"Why is the node down\"}"'
拆解每一步的作用
.nodes:先定位到JSON里的nodes对象to_entries[]:把nodes里的键值对转换成{key: "节点名", value: 节点信息对象}的结构,这是获取节点名最实用的方式(比单独用.keys更方便结合后续的状态判断)select(.value.state != "free"):筛选出state不等于"free"的节点条目"\(.key): {comment: \"Why is the node down\"}":用字符串插值把节点名替换进去,输出你要的格式
单独获取节点名的几种方式
- 拿到所有节点名:
some-command | jq '.nodes | keys' - 只拿到state不为free的节点名:
some-command | jq '.nodes | to_entries[] | select(.value.state != "free") | .key'
示例验证
假设你的输入JSON是这样:
{
"timestamp": "2024-05-20T10:00:00Z",
"nodes": {
"node1": {"state": "free", "comment": "Idle"},
"node2": {"state": "down", "comment": "Maintenance"},
"node3": {"state": "busy", "comment": "Running task"}
}
}
运行第一条命令后,输出会是:
node2: {comment: "Why is the node down"} node3: {comment: "Why is the node down"}
内容的提问来源于stack exchange,提问作者William Allcock
相关产品推荐
相关产品推荐

