简体   繁体   中英

Json parsing on cli using jq

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 '.abcfoo'

I realize I can do... echo '{ "a":{"b":{"c":{ "foo":1}}},"d":{"e":{"bar":2}}}' | jq '.[][][].foo' 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM