简体   繁体   English

如何使用jq在JSON对象中查找值匹配给定条件的所有路径?

[英]How can I use jq to find all paths in a JSON object under which a value matches a given criteria?

Is there a way I could use jq to find all paths that hold a value that matches a given criteria? 有没有一种方法可以使用jq查找具有与给定条件匹配的值的所有路径?

For example, given the following JSON, I'd like to return all paths where the value of "age" is >35, regardless of the depth of the structure containing that field: 例如,给定以下JSON,无论包含该字段的结构的深度如何,我都希望返回“ age”的值大于35的所有路径:

{  
  "springfield":{  
    "marge":{  
      "age":30
    },
    "homer":{  
      "age":40,
      "job":"xyz"
    }
  },
  "shelbyville":{  
    "zone1":{  
      "john":{  
        "age":10
      }
    },
    "zone2":{  
      "mark":{  
        "age":50
      }
    }
  },
  "homeless1":{  
    "age":25
  },
  "homeless2":{  
    "age":60
  }
}

So the execution would yield something like: 因此执行将产生如下结果:

[
  ["springfield", "homer"],
  ["shelbyville", "zone2", "mark"],
  ["homeless2"]
]

这应该可以解决问题:

[paths(.age?>35)]

The following has been tested with jq 1.4 and jq 1.5: 以下已通过jq 1.4和jq 1.5进行了测试:

$ jq -M -c '(paths | select(.[length-1] =="age")) as $path
    | if (getpath($path) > 35) then $path else empty end' ages.json
["springfield","homer","age"]
["shelbyville","zone2","mark","age"]
["homeless2","age"]

The following requires jq 1.5: 以下要求jq 1.5:

$ jq -c --stream 'select(length == 2 and .[0][-1] == "age" 
    and .[1] > 35)' ages.json
[["springfield","homer","age"],40]
[["shelbyville","zone2","mark","age"],50]
[["homeless2","age"],60]

These can both easily be adapted to produce similar output. 这些都可以轻松调整以产生相似的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM