You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jq或grep过滤JSON,提取__pod_controller_name为podIwant的完整记录

过滤指定字段值的JSON记录

假设你有如下多条独立的JSON记录(非JSON数组):

{
  "endpoint": "http://10.225.25.33:8080/metrics",
  "properties": {
    "__pod_name": "pod1",
    "__pod_controller_name": "podIwant"
  }
}
{
  "endpoint": "http://10.225.10.21:8080/metrics",
  "properties": {
    "__pod_name": "pod2",
    "__pod_controller_name": "podIdontwant"
  }
}
{
  "endpoint": "http://10.225.33.52:8080/metrics",
  "properties": {
    "__pod_name": "pod3",
    "__pod_controller_name": "podIwant"
  }
}

使用jq工具(推荐)

jq能精准处理JSON结构,适配多条独立JSON的场景:

jq -n 'inputs | select(.properties.__pod_controller_name == "podIwant")' input.json
  • -n:让jq用inputs遍历每个独立的JSON实体,而非默认读入单一变量
  • select(...):筛选出properties.__pod_controller_name值为podIwant的完整JSON记录

执行后输出结果:

{
  "endpoint": "http://10.225.25.33:8080/metrics",
  "properties": {
    "__pod_name": "pod1",
    "__pod_controller_name": "podIwant"
  }
}
{
  "endpoint": "http://10.225.33.52:8080/metrics",
  "properties": {
    "__pod_name": "pod3",
    "__pod_controller_name": "podIwant"
  }
}

使用grep工具(仅适用于格式固定场景)

若没有jq,可借助grep的上下文匹配,前提是JSON格式稳定:

grep -B5 -A2 '"__pod_controller_name": "podIwant"' input.json
  • -B5:取匹配行前5行(覆盖JSON对象开头到目标字段的内容)
  • -A2:取匹配行后2行(覆盖目标字段到JSON对象结尾的内容)

注意:如果JSON换行格式变化,需调整-B和-A的行数,这种方法可靠性不如jq。

内容的提问来源于stack exchange,提问作者SugusTHC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 16:02:13