Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter by key

Tags:

json

jq

I have this sort of json:

[
    {
        "source": 
        {
            "file": "test",
            "baz": "now"
        }
    },
    {
        "source": {
            "dev": "foo"
        }
    },
    
    {
        "source": {
            "bar": "bar"
        }
    }
]

and I would like to get a list of all values for file or dev. So the expected outcome of the above should be: ["test", "foo"]

I am stuck somewhere here:

.[].source | select(.file? or .dev?)

But that yield the complete objects. How to access only the attribute values than??

like image 700
philipp Avatar asked Mar 13 '26 14:03

philipp


2 Answers

You can traverse to .file and .dev at once using .source | .file, .dev or .source["file", "dev"], then filter out null values using values (not ?).

map(.source | .file, .dev | values)
# or
map(.source["file", "dev"] | values)
[
  "test",
  "foo"
]
like image 100
pmf Avatar answered Mar 16 '26 05:03

pmf


Instead of using ? or other operators, using getpath/1 is one option, where you can just filter paths and get their value

[ getpath(paths | select(.[-1] == "file" or .[-1] == "dev")) ]

Or even combine with another condition to check for source key, if you want to be completely sure i.e. .[-2] == "source"

Demo - https://jqplay.org/s/IddhVIbUenj

like image 28
Inian Avatar answered Mar 16 '26 05:03

Inian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!