Search code examples
bashjqi3

How to get subtree of json containing known object


I want to extract the subtree containing the focused window from i3-msg -t get_tree with jq. I know the focused window can be found with

i3-msg -t get_tree | jq ".. | (.nodes? // empty)[] | select(.focused == true)"

A simple example would be:

{
  "node": [
    {
      "node": {
        "foo": "bar"
      }
    },
    {
      "node": {
        "foo": "foo"
      }
    }
  ]
}

And the output should if searching for a node containg .foo == "bar" should return

{
  "node": [
    {
      "node": {
        "foo": "bar"
      }
    }
  ]
}

But I can't seem to find a proper method to extract the subtree spanning from the root to this node.


Solution

  • .node |= map(select(.node.foo == "bar"))
    

    This concept is referred to as Update assignment