Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filtering Json output with jq or grep

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading