jsonjmespath

How can I apply a filter projection ([?port == `eth1`]) on top of an object projection (*)?


I have a data structure like that

{
  "lan": {
    "main_router": {
      "ip": "192.168.22.1",
      "port": "eth1"
    }
  },
  "guest": {
    "main_router": {
      "ip": "192.168.44.1",
      "port": "eth1.44"
    }
  },
  "iot": {
    "main_router": {
      "ip": "192.168.66.1",
      "port": "eth1.66"
    }
  }
}

and I want to get all main_router entries where the value of port is eth1.

I tried the following two queries on the jmespath.org tutorial:

*.main_router[?port==`eth1`]
*[?main_router.port==`eth1`]

but neither this two nor the many variations I tried did yield any result at all.


Solution

  • This is because * is an object projection and if you want to apply a projection on the result of another projection — and not on the projection itself — you need to stop the first projection, with the help of a pipe expression.

    Which you can apply to either of your trial:

    *.main_router | [?port == `eth1`]
    

    Would give you:

    [
      {
        "ip": "192.168.22.1",
        "port": "eth1"
      }
    ]
    

    While

    * | [?main_router.port == `eth1`]
    

    Would give you:

    [
      {
        "main_router": {
          "ip": "192.168.22.1",
          "port": "eth1"
        }
      }
    ]