Question

Let's say I have the below json object:

{
  "d": {
    "e": {
      "bar": 2
    }
  },
  "a": {
    "b": {
      "c": {
        "foo": 1
      }
    }
  }
}

I want to get the value foo without typing '.a.b.c.foo'

I realize I can do... echo '{ "a":{"b":{"c":{ "foo":1}}},"d":{"e":{"bar":2}}}' | jq '.[][][].foo' but is there a recursive wild in jq? like **? I know for sure jq doesn't support *, is there a way to have jq support jsonpath? Or maybe even just another cli tool that does support json path?

Was it helpful?

Solution

In jq 1.4 you could do this:

$ jq '..|.foo?' file.json

If you're stuck with 1.3 you could use

$ jq 'recurse(if type == "array" or type == "object" then .[] else empty end) | if type == "object" then . else empty end | .foo' file.json

which is a bit of a mouthful... That's why 1.4 has .., which recurses down through all iterables in ., and the ? operator, which doesn't bother indexing that which can't be.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top