0

I have a Json with this kind of records and I want to filter it using jq or grep to get an output with only the full records where "__pod_controller_name" its "podIwant"

{
  "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"
  }
}

I've been trying with a lot of jq and map commands but I could not. Thanks.

SugusTHC
  • 37
  • 4
  • Does this answer your question? [How to filter array of objects by element property values using jq?](https://stackoverflow.com/questions/38121740/how-to-filter-array-of-objects-by-element-property-values-using-jq) – knittl Apr 27 '23 at 16:37

1 Answers1

0

For structured data like JSON, use appropriate tools like jq, not grep. With jq, you can filter using select. It takes some filter, and if it evaluates to true its input is passed on.

jq 'select(.properties.__pod_controller_name == "podIwant")' input.json

If you want the query string to be dynamic (adjustable from the calling environment), use the --arg flag to bind it to a variable:

jq --arg name 'podIwant' 'select(.properties.__pod_controller_name == $name)' input.json

Output:

{
  "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"
  }
}

Demo

pmf
  • 24,478
  • 2
  • 22
  • 31
  • THANKS a lot. How could be if i'm looking to output the records that does not match perfectly with the value but contains the string i want? If "__pod_controller_name" is "12.podIwant.1.3" and the other one I want is "34.podIwant.2.3". I cannot make it work using contain instead of == :/ – SugusTHC Apr 27 '23 at 16:46
  • 1
    @SugusTHC You can use `contains` ([manual](https://stedolan.github.io/jq/manual/#contains(element))) for a partial matching or `test` ([manual](https://stedolan.github.io/jq/manual/#test(val),test(regex;flags))) for a full regex matching. [Here](https://jqplay.org/s/bwTNp-frZk3) is a demo how to use `contains` on the strings given. – pmf Apr 27 '23 at 16:48