jq return all arrays that match one field

Viewed 365

I am trying to grab all the arrays that match an element but am having trouble returning everything.

Data

cat testerr.json | jq .''

{
  "circuitIdNum": 1226,
  "description": "9287-customer:vpn-2001226-(R1-Loopback0)",
  "interfaceId": "1040",
  "ipv4": {
    "aclEgress": "rot-out",
    "addr": "55.44.53.191/31",
    "bgpNeighbor": "33.567.53.190"
  },
  "loadInterval": 30,
  "remoteRouter": "R1-Loopback0",
  "shortName": "rot",
  "tunnel": {
    "destination": "94.252.78.14",
    "source": "66.52.5.4"
  }
}
{
  "circuitIdNum": 1227,
  "description": "9287-customer:vpn-2001227-(R2-Loopback0)",
  "interfaceId": "1041",
  "ipv4": {
    "aclEgress": "rot-out",
    "addr": "23.77.175.253/31",
    "bgpNeighbor": "21.44.175.252"
  },
  "loadInterval": 30,
  "remoteRouter": "R2-Loopback0",
  "shortName": "rot",
  "tunnel": {
    "destination": "22.22.18.15",
    "source": "1.5.55.5"
  }
}

This kind of works but only provides Destination and Source.

cat testerr.json | jq .'tunnel | select(.source | contains ("1.5.55."))'

{
  "destination": "22.22.18.15",
  "source": "1.5.55.5"
}

Instead of only reply the tunnel section I want it to return the full array.

{
  "circuitIdNum": 1227,
  "description": "9287-customer:vpn-2001227-(R2-Loopback0)",
  "interfaceId": "1041",
  "ipv4": {
    "aclEgress": "rot-out",
    "addr": "23.77.175.253/31",
    "bgpNeighbor": "21.44.175.252"
  },
  "loadInterval": 30,
  "remoteRouter": "R2-Loopback0",
  "shortName": "rot",
  "tunnel": {
    "destination": "22.22.18.15",
    "source": "1.5.55.5"
  }
}

My attempts are all over the place atm. Im not sure how to call the top level and search elements a few levels in. Thanks

1 Answers

Simply have your select() refer to the nested field, that will return the whole top-level element.

$ cat testerr.json | jq 'select(.tunnel.source | contains ("1.5.55."))'
{
  "circuitIdNum": 1227,
  "description": "9287-customer:vpn-2001227-(R2-Loopback0)",
  "interfaceId": "1041",
  "ipv4": {
    "aclEgress": "rot-out",
    "addr": "23.77.175.253/31",
    "bgpNeighbor": "21.44.175.252"
  },
  "loadInterval": 30,
  "remoteRouter": "R2-Loopback0",
  "shortName": "rot",
  "tunnel": {
    "destination": "22.22.18.15",
    "source": "1.5.55.5"
  }
}
Related