gdoubleod gdoubleod - 1 year ago 109
JSON Question

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

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download